Advertisement
alansam

Insertion Sort

Jun 10th, 2023 (edited)
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | Source Code | 0 0
  1. // IS this code okay for insertions sort? it gives correct awnser
  2.  
  3. #include <iostream>
  4. #include <iomanip>
  5. #include <vector>
  6. #include <array>
  7.  
  8. void insert(int array[], int size) {
  9.   for (int j = 0; j < size; j++) {
  10.     for (int i = 1; i < size; i++) {
  11.       if (array[i] < array[i - 1]) {
  12.         std::swap(array[i], array[i - 1]);
  13.       }
  14.     }
  15.   }
  16. }
  17.  
  18. /*
  19.  *  pseudocode
  20.  *  @see: https://en.wikipedia.org/wiki/Insertion_sort
  21.  *
  22.  *  i ← 1
  23.  *  while i < length(A)
  24.  *    j ← i
  25.  *    while j > 0 and A[j-1] > A[j]
  26.  *      swap A[j] and A[j-1]
  27.  *      j ← j - 1
  28.  *    end while
  29.  *    i ← i + 1
  30.  *  end while
  31.  */
  32. void insert(std::vector<int> & vect) {
  33.   auto i_ { 1ul };
  34.   while (i_ < vect.size()) {
  35.     auto j_ { i_ };
  36.     while (j_ > 0 && vect[j_ - 1] > vect[j_]) {
  37.       std::swap(vect[j_], vect[j_ - 1]);
  38.       j_--;
  39.     }
  40.     i_++;
  41.   }
  42. }
  43.  
  44. /*
  45.  *  RosettaCode
  46.  *  @see: https://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#top-page
  47.  *
  48.  *  function insertionSort(array A)
  49.  *    for i from 1 to length[A]-1 do
  50.  *      value := A[i]
  51.  *      j := i-1
  52.  *      while j >= 0 and A[j] > value do
  53.  *        A[j+1] := A[j]
  54.  *        j := j-1
  55.  *      done
  56.  *      A[j+1] = value
  57.  *    done
  58.  */
  59. void insertionSort(std::array<int, 5> & ary) {
  60.   for (auto i_ { 1ul }; i_ < ary.size() - 1ul; ++i_) {
  61.     auto value = ary[i_];
  62.     auto j_ = i_ - 1ul;
  63.     while (j_ > 0ul && ary[j_] > value) {
  64.       ary[j_ + 1] = ary[j_];
  65.       j_--;
  66.     }
  67.     ary[j_ + 1] = value;
  68.   }
  69. }
  70.  
  71. int main() {
  72.   auto show = [](auto const & ary) {
  73.     for (auto val : ary) {
  74.       std::cout << std::setw(4) << val;
  75.     }
  76.     std::cout << std::endl;
  77.   };
  78.  
  79.   int array[] = { 12, 71, 22, 67, 45, };
  80.   size_t constexpr size = sizeof array / sizeof *array;
  81.  
  82.   show(array);
  83.   insert(array, size);
  84.   show(array);
  85.   std::cout << std::endl;
  86.  
  87.   std::vector<int> vect { 102, 701, 202, 607, 405, };
  88.  
  89.   show(vect);
  90.   insert(vect);
  91.   show(vect);
  92.   std::cout << std::endl;
  93.  
  94.   std::array<int, 5> ary { 112, 711, 212, 617, 415, };
  95.  
  96.   show(ary);
  97.   insertionSort(ary);
  98.   show(ary);
  99.   std::cout << std::endl;
  100.  
  101.   return 0;
  102. }
  103.  
Tags: #sort
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement