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
Components in a graph
There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu
View Solution →Kundu and Tree
Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that
View Solution →Super Maximum Cost Queries
Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and
View Solution →Contacts
We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co
View Solution →No Prefix Set
There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio
View Solution →Cube Summation
You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor
View Solution →