-
April 18th, 2015, 11:36 PM
#1
Selection Sort is not magic! What's going on?
I just noticed something about selection sort that I overlooked:
7 was smaller than 16 first.
How does my selection sort function know that 5 exists even though a linear search would encounter 7 first (since 7 is also smaller than 16)? It can't be the result of a binary search either, because the data hasn't even finished getting sorted yet. So what's going on?
Code:
void selectionSort(int arr[], int n)
{
int smallestIndex;
int smallest, saved;
for (int i = 0; i < n - 1; i++) {
// Find smallest element
smallest = arr[i];
smallestIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
smallestIndex = j;
}
}
// Swap with smallest element
saved = arr[i];
arr[i] = arr[smallestIndex];
arr[smallestIndex] = saved;
}
}
-
April 19th, 2015, 12:52 AM
#2
Re: Selection Sort is not magic! What's going on?
Originally Posted by UncleBazerko
How does my selection sort function know that 5 exists even though a linear search would encounter 7 first (since 7 is also smaller than 16)? It can't be the result of a binary search either, because the data hasn't even finished getting sorted yet. So what's going on?
Upon encountering 7, 7 becomes the new smallest known element, so by the time 5 is encountered, 5 being less than 7, 5 becomes the new smallest known element.
-
April 19th, 2015, 03:37 AM
#3
Re: Selection Sort is not magic! What's going on?
Originally Posted by UncleBazerko
...
How does my selection sort function know that 5 exists even though a linear search would encounter 7 first (since 7 is also smaller than 16)? It can't be the result of a binary search either, because the data hasn't even finished getting sorted yet. So what's going on?
It is because you do not break the inner loop after finding the first number being smaller, but continue the search and comparison until the end of array.
Victor Nijegorodov
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|