vanllabean81

Selection Sort

Jul 18th, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.     int main()
  5.     {
  6.             int ary[10] = {10,5,16,28,55,100,90,14,15,31};// Declare array of 10
  7.             int end = 9;       // Variable for last position in array
  8.             int biggest;       // Variable to hold value of largest #
  9.             int pos = 0;       // Variable to hold position where largest value is found
  10.  
  11.             for (int i = 0; i < end; i++)       // For n - 1 passes
  12.             {
  13.                     biggest = ary[0];           // Set first array value to the variable that holds biggest
  14.                     for (i = 0; i <= end; i++)   // For all elements in array
  15.                     {
  16.                        if (ary[i] > biggest)    // If biggest element is larger than second element
  17.                         {
  18.                             biggest = ary[i];   // Set that value to 'biggest'
  19.                             pos = i;            // Hold this position #
  20.                         }
  21.                         else if (ary[1] < ary[0])// I know this is crappy, but I can't figure out how to do it better.
  22.                         {
  23.                             int temp = ary[i+1]; // Sweap the first two elements if second is less than first
  24.                             ary[i+1] = ary[i];
  25.                             ary[i] = temp;
  26.                         }
  27.                     }
  28.                     ary[pos] = ary[end];        // Once we found biggest # in array, swap end value with
  29.                     ary[end] = biggest;         // biggest position's value
  30.                     end--;                      // Stop including last # in search
  31.                     i = 0;                      // Now we start over again to find the next largest #
  32.             }
  33.                                                 // Now the list we compare is one shorter
  34.             end = 9;                            // Reset end back to 9
  35.             for (int p = 0; p <= end; p++)      // For all elements in array
  36.                     cout << ary[p] << endl;     // Print elements
  37.     }
Advertisement
Add Comment
Please, Sign In to add comment