Advertisement
ivanwidyan

Insertion Sort With Custom Array Size

Oct 24th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int findSmallestRemainingElement(int array[], int size, int index);
  7. void swap(int array[], int first_index, int second_index);
  8.  
  9. void sort(int array[], int size) {
  10.     for (int i = 0; i < size; i++) {
  11.         int index = findSmallestRemainingElement(array, size, i);
  12.         swap(array, i, index);
  13.     }
  14. }
  15.  
  16. int findSmallestRemainingElement(int array[], int size, int index) {
  17.     int index_of_smallest_value = index;
  18.     for (int i = index + 1; i < size; i++) {
  19.         if (array[i] < array[index_of_smallest_value]) {
  20.             index_of_smallest_value = i;
  21.         }
  22.     }
  23.     return index_of_smallest_value;
  24. }
  25. void swap(int array[], int first_index, int second_index) {
  26.     int temp = array[first_index];
  27.     array[first_index] = array[second_index];
  28.     array[second_index] = temp;
  29. }
  30. // small helper method to display the before and after arrays
  31. void displayArray(int array[], int size) {
  32.     cout << "{";
  33.     for (int i = 0; i < size; i++) {
  34.         // you'll see this pattern a lot for nicely formatting
  35.         // lists--check if we're past the first element, and
  36.         // if so, append a comma
  37.         if (i != 0) {
  38.             cout << ", ";
  39.         }
  40.         cout << array[i];
  41.     }
  42.     cout << "}";
  43. }
  44.  
  45. int main() {
  46.     int arraySize;
  47.     cout << "Put The Size of The Array: ";
  48.     cin >> arraySize;
  49.     int *array = new int[arraySize];
  50.     srand(time(NULL));
  51.     for (int i = 0; i < arraySize; i++) {
  52.         // keep the numbers small so they're easy to read
  53.         array[i] = rand() % 100;
  54.     }
  55.     cout << "Original array: ";
  56.     displayArray(array, arraySize);
  57.     cout << '\n';
  58.     sort(array, arraySize);
  59.     cout << "Sorted array: ";
  60.     displayArray(array, arraySize);
  61.     cout << '\n';
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement