Hello There, Guest! (LoginRegister)

Post Thread  Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Selection Sort - C++
05-04-2007, 07:24 PM
Post: #1
Selection Sort - C++
[SIZE="4"]Selection Sort[/SIZE]

Source : http://www.AquireKnowledge.com

For this week I'll move onto the selection sort. The selection sort is another simple algorithm. Look through the unsorted elements of the list and find the minimum element and swap with the first unsorted element until all elements have been sorted. Here's the code for the sort:



void SelectionSort(int* elems, int numElems)
{
int minIndex;
int minVal;
for(i=0; i < numElems - 1; ++i)
{
minIndex = i;
minValue = elems[i]
for(j=i + 1; j < numElems; ++j)
if (elems[j] < minValue)
{
minIndex = j;
minValue = elems[j];
}
swap(elems[i], elems[j]);
}
}


A few things about the sort:
Best Case sorting time: O(n^2)
Stable: No

This sort doesn't have a best/worst case time. The time it takes to sort a list completely is always O(n^2). So, if this sort is always going to run slowly, why bother use it at all? Well, it's useful to find the top or bottom m elements, where m<<n (m is signicantly less than n), and you don't care about stability. Also, it's one of the foundation sorts that some of the other more complex algorithms fall back upon. The Shell sort is one such sort.

Again, if there are any ideas on improving the algorithm, don't be shy to share them. Please, keep the improvements to the algorithm and don't be caught up in small optimizations.
Find all posts by this user
Quote this message in a reply
12-22-2007, 05:35 PM
Post: #2
 
Thank you - but I think everybody can fetch his tutorials himself, isn't it?
At least, you could [code] your code
[code]void SelectionSort(int* elems, int numElems)
{
int minIndex;
int minVal;
for(i=0; i < numElems - 1; ++i)
{
minIndex = i;
minValue = elems[i]
for(j=i + 1; j < numElems; ++j)
if (elems[j] < minValue)
{
minIndex = j;
minValue = elems[j];
}
swap(elems[i], elems[j]);
}
}[/code]
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: