Originally posted by: hoppa
Originally posted by: sao123
If you sort the entire array obviously its going to be O(n^2), because thats what bubblesort is. If you sort only the 10 largest elements.... its O(n)
Sao, that's fine but that still only applies to X = 10. If you want this for any X, which is a million times more useful, than it is still O(n^2).
Not neccessarily... if you read and play with the sorting algorithms, each one has its own disadvantages and advantages depending on the nature of the application, and the randomness of the array (guassian, random, reversed sorted, etc).
For my application where I only wanted the ten largest elements in a huge array, the obvious non-recursive sort algorithm of choice was bubblesort since by nature, after N passes through the array, the first N elements are going to be the largest.
Now I'm no CS major, but making 10 passes through a 1+million array using bubblesort to get the ten largest elements was expensive and unacceptable. So, I modified the algorithm slightly so that it's roughly O(n), and it's surprisingly simple, and very fast, AND leaves even more room to optimize.
The psuedocode goes something like this:
1. Create 10 element sorted array with initial values being 0.
2. Step through each element in the array.
3. If big array element[n] > last element in sorted array, replace last element in sorted array with element[n].
4. Re-sort 10 element array.
5. Repeat #2 until you go through all elements in the big array.
Now, I know some of you are going to argue that this is only going to work for N (10 in this case) largest elements... and that's EXACTLY all I need for this application. As N increases, this algorithm becomes grossly inefficient. For my application, on average there will be about 0.5*sizeof(big array) sorts on the 10 element array, and that can be sorted very quickly with just about any algorithm.
The reason I say there's room for improvement is because in step #4, after the first 10 elements are inserted into the sorted array, every other element inserted will only replace the last element. That means that the last element will be the only element unsorted in that array. Again, using bubblesort only requires 1 pass through the array to resort that sorted array.