Advertisement
sheffield

Array Sort

Jul 20th, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. Program: Array Sort
  2.  
  3. #include <algorithm> // for std::swap, use <utility> instead if C++11
  4. #include <iostream>
  5. #define SIZE 10
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.  
  11.     cout<<"array values :"<<" 132, 520, 210, 510, 140 ,125,52,96,55,85"<<"\n";
  12.     //input array values
  13.     int array[SIZE] = { 132, 520, 210, 510, 140 ,125,52,96,55,85 };
  14.  
  15.     cout<<"sorted values : ";
  16.  
  17.     // Step through each element of the array
  18.     for (int startIndex = 0; startIndex < SIZE; ++startIndex)
  19.     {
  20.         // smallestIndex is the index of the smallest element we've encountered so far.
  21.         int smallestIndex = startIndex;
  22.  
  23.         // Look for smallest element remaining in the array (starting at startIndex+1)
  24.         for (int nowIndex = startIndex + 1; nowIndex < SIZE; ++nowIndex)
  25.         {
  26.             // If the current element is smaller than our previously found smallest
  27.             if (array[nowIndex] < array[smallestIndex])
  28.             // This is the new smallest number for this iteration
  29.             {
  30.                 smallestIndex = nowIndex;
  31.             }
  32.         }
  33.  
  34.         // Swap our start element with our smallest element
  35.         swap(array[startIndex], array[smallestIndex]);
  36.     }
  37.  
  38.     // Now print our sorted array as proof it works
  39.     for (int index = 0; index < SIZE; ++index)
  40.     {
  41.         cout << array[index] << ' ';
  42.     }
  43.  
  44.     cout<<"\n";
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement