Tuesday, July 28, 2009

What is the best sorting algorithm for c++?

for class assignment

What is the best sorting algorithm for c++?
Well along with simplicity it is insertion sort.





It works like this:-





Consider a small -%26gt; large alphabetic sorting.


say a list LIST [ MAXLISTITEMS ] exits; which is unsorted.





We compare an element, say K from this list (that falls between the 2nd and Last elements inclusive) to the element preceding it. That is the i-th element (where, i=2 to no of list items) with the elements through the 1st element to the i-1 th element. If the element K is smaller, we swap values and resume the process without any break.





In C:





for( i=1; i%26lt;n; i++) {


for( j=0; j%26lt;i-1; j++) {


if( LIST[j] %26lt; LIST[i] ) {


swap( LIST[i], LIST[j] );


}


}


}
Reply:Sorting algorithms are not specific to a given language. What matters is not the language, but the number of elements you want to sort. For a small number of elements, O(n-squared) can be faster than O(n*logn); whereas the reverse is true for a large number of elements. You may want to Google "quicksort", "mergesort", "bubblesort", and "insertionsort".





If you are not required to implement the sorting algorithm, yourself, and you only need to use a sorting algorithm, then you should look up the documentation for "std::sort". The "std::sort" function, on most implementations, is more optimized than any sorting algorithm you would write.
Reply:That depends on what you are trying to sort.





Perhaps one of the easiest to implement is bubble sort.





Then you have quicksort. Also there is merge sort (if you are starting with lists that are already sorted, but you need to sort the lists into a larger sorted list). There are other sorting algorithms.





Can you give more detail? Also, if you know the run times (Big-O?) then that will help you determine some of the best algorithms, but the best aren't always the easiest to implement.





You should also look here:


http://en.wikipedia.org/wiki/Sorting_alg...
Reply:You can use either selection sort or bubble sort


C++ code for


selection sort


void selectionSort(int numbers[], int array_size)


{


int i, j;


int min, temp;





for (i = 0; i %26lt; array_size-1; i++)


{


min = i;


for (j = i+1; j %26lt; array_size; j++)


{


if (numbers[j] %26lt; numbers[min])


min = j;


}


temp = numbers[i];


numbers[i] = numbers[min];


numbers[min] = temp;


}


}








bubble sort


void bubbleSort(int numbers[], int array_size)


{


int i, j, temp;





for (i = (array_size - 1); i %26gt;= 0; i--)


{


for (j = 1; j %26lt;= i; j++)


{


if (numbers[j-1] %26gt; numbers[j])


{


temp = numbers[j-1];


numbers[j-1] = numbers[j];


numbers[j] = temp;


}


}


}


}


No comments:

Post a Comment