CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2015
    Posts
    64

    Selection Sort is not magic! What's going on?

    I just noticed something about selection sort that I overlooked:
    Name:  selectionSort.PNG
Views: 361
Size:  44.3 KB
    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;
    	}
    }

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Selection Sort is not magic! What's going on?

    Quote 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.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Selection Sort is not magic! What's going on?

    Quote Originally Posted by UncleBazerko View Post
    ...
    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
  •  





Click Here to Expand Forum to Full Width

Featured