Running Time of Algorithms
Problem Statement :
n a previous challenge you implemented the Insertion Sort algorithm. It is a simple sorting algorithm that works well with small or mostly sorted data. However, it takes a long time to sort large unsorted data. To see why, we will analyze its running time. Running Time of Algorithms The running time of an algorithm for a specific input depends on the number of operations executed. The greater the number of operations, the longer the running time of an algorithm. We usually want to know how many operations an algorithm will execute in proportion to the size of its input, which we will call . What is the ratio of the running time of Insertion Sort to the size of the input? To answer this question, we need to examine the algorithm. Analysis of Insertion Sort For each element in an array of numbers, Insertion Sort compares the number to those to its left until it reaches a lower value element or the start. At that point it shifts everything to the right up one and inserts into the array. How long does all that shifting take? In the best case, where the array was already sorted, no element will need to be moved, so the algorithm will just run through the array once and return the sorted array. The running time would be directly proportional to the size of the input, so we can say it will take time. However, we usually focus on the worst-case running time (computer scientists are pretty pessimistic). The worst case for Insertion Sort occurs when the array is in reverse order. To insert each number, the algorithm will have to shift over that number to the beginning of the array. Sorting the entire array of numbers will therefore take operations, which is (almost ). Computer scientists just round that up (pick the dominant term) to and say that Insertion Sort is an " time" algorithm. Challenge Can you modify your previous Insertion Sort implementation to keep track of the number of shifts it makes while sorting? The only thing you should print is the number of shifts made by the algorithm to completely sort the array. A shift occurs when an element's position changes in the array. Do not shift an element if it is not necessary. Function Description Complete the runningTime function in the editor below. runningTime has the following parameter(s): int arr[n]: an array of integers Returns int: the number of shifts it will take to sort the array Input Format The first line contains the integer n, the number of elements to be sorted. The next line contains n integers of arr[ arr[0] . . .arr[ n - 1 ] ] .
Solution :
Solution in C :
In C++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int insertionSortCount(vector <int> ar) {
int n = ar.size();
int count=0;
for(int i=1;i<n;i++){
int curr = ar[i];
for(int j=i-1;j>=0;j--){
if(ar[j]>curr){
ar[j+1]=ar[j];
count++;
if(j==0)
ar[j]=curr;
}
else{
ar[j+1]=curr;
j=-1;
}
}
}
return count;
}
/* Tail starts here */
int main() {
vector <int> _ar;
int _ar_size;
cin >> _ar_size;
for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
int _ar_tmp;
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
cout<<insertionSortCount(_ar);
return 0;
}
In Java :
/* Head ends here */
import java.util.*;
public class Solution {
static void insertionSort(int[] ar) {
int count =0;
for(int i=1;i<ar.length;i++){
int n= ar[i];
int j=i-1;
while(j>=0 && ar[j]>n){
//System.err.print(i+" ");
ar[j+1]=ar[j]; //shift right
j--;
count++;
}
ar[j+1]= n;
}
System.out.println( count);
}
/* Tail starts here */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i=0;i<n;i++){
ar[i]=in.nextInt();
}
insertionSort(ar);
}
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
/* Head ends here */
void insertionSort(int ar_size, int * ar,int *shifts) {
int temp=ar[ar_size-1],i;
for(i=ar_size-2;i>=0;i--)
{
if(ar[i]>temp){ ar[i+1]=ar[i];*shifts=*shifts+1;}
else break;
//for(j=0;j<ar_size;j++)printf("\n%d",ar[j]);
}
ar[i+1]=temp;
}
/* Tail starts here */
int main() {
int _ar_size,i,j,shifts=0;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
scanf("%d", &_ar[_ar_i]);
}
for(i=2;i<=_ar_size;i++)
{insertionSort(i, _ar,&shifts);
}
printf("%d",shifts);
return 0;
}
In Python3 :
size = int(input())
array = input().split(" ")
arr = ['None'] * size
for i in range(size):
arr[i] = int(array[i])
i = 1
count = 0
while i < size:
tmp = arr[i]
j = i - 1
while arr[j] > tmp and j > -1:
arr[j+1] = arr[j]
j = j - 1
count = count + 1
arr[j+1] = tmp
i = i + 1
print(count)
View More Similar Problems
Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →