Find the big-O running time of a sorting program that does the following:
At the end, the list is sorted low to high.
(Also, try implementing this program in your language of choice.)
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The total number of operations should be (n(n+1))/2, right?
Log in to reply
@Jiayun Zhao , I believe you are right. The total count is 2 n ( n + 1 ) , not 2 n ( n − 1 ) , but the final answer is still O ( n 2 ) .
if there is n item then total number of comparison is (n-1),so series starts with (n-1)and total count = ((n-1)n)/2, right?
int [] arr = new int []{1,4,3,2};
for(int j=0; j< arr.Length; j++)
{
// find larget element
int maxIndex = 0;
for(int i=0; i<arr.Length - j; i++)
{
if(arr[i] > arr[maxIndex])
{
maxIndex = i;
}
}
// move to the last
var temp = arr[arr.Length -1 - j];
arr[arr.Length -1 - j] = arr[maxIndex];
arr[maxIndex] = temp;
// sort remaining list
}
for(int i=0; i< arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
This is simply selection sort.... http://en.wikipedia.org/wiki/Selection_sort
Yes, it is ( I didn't say that above because then people could easily look it up).
I wanted to find an algorithm I could easily explain without catering to any language.
For Python lovers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The algorithm will have nested loop (2 loops; one inside the other) and the complexity of two nested loops is n2.
list will have to be iterated through once per element, therefore, the list will be iterated through n*n times
loop an array of N element around N times makes NxN complexity
Problem Loading...
Note Loading...
Set Loading...
For a list of integers that is n items long:
The program does one operation (comparison of two numbers) per item in the list. This adds n operations. Next, it iterates over the remaining integers. This adds n − 1 operations. By the end, the total amount of operations is n + ( n − 1 ) + ( n − 2 ) + . . . + 3 + 2 + 1 , and this can be expressed in closed form as n + . . . + 2 + 1 = 2 n ( n − 1 ) = 2 1 n 2 − 2 1 n .
When finding the big-O running time of a program, we must only consider the asymptotic behavior of its running time, so we can ignore the addition of "slower" terms, and we can ignore coefficients. This leaves us with,
O ( 2 1 n 2 − 2 1 n ) = O ( n 2 − n ) = O ( n 2 )