Home c++ Sorting C++ selection method

Sorting C++ selection method

Author

Date

Category

There are two arrays of the same size, one filled with numbers, the second is empty. It is necessary to sort by selecting a first array in a second, without changing the first. In this case, copy the first array in the second.


Answer 1

That is, the Wikipedia, there is a link

https: // ru.wikipedia.org/wiki/%D0%A1%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0_%D0 % B2% D1% 8B% D0% B1% D0% BE% D1% 80% D0% BE% D0% BC

Once you want to change is not the first array, why not store the second index of the first array and not rearrange the elements of the first array and the second array indices?

void studip_sort (int * src, int * dst, const int size) {
  // put each element dst its index
  for (int i = 0; i & lt; size; i ++) {
    dst [i] = i;
  }
  // sort the array
  for (int i = 0; i & lt; size - 1; i ++)
  {
    int min_index = i;
    for (int j = i + 1; j & lt; size; j ++)
    {
      if (src [dst [j]] & lt; src [dst [min_index]])
      {
        min_index = j;
      }
    }
    if (min_index! = i)
    {
      const int tmp = dst [min_index];
      dst [min_index] = dst [i];
      dst [i] = tmp;
    }
  }
  // put each element value of the src dst
  for (int i = 0; i & lt; size; i ++) {
    dst [i] = src [dst [i]];
  }
}
INT MAIN () {
  int src [20] = {1, 6, 9, 11, 0, -3, 4, 5, 11, 6, 7, 7, -8, 11, 20, -11, 0, -3, 1, 5 };
  int dst [20];
  studip_sort (src, dst, 20);
  for (int i = 0; i & lt; 20; i ++) {
    STD :: COUT & LT; & LT; dst [i] & lt; & lt; "";
  }
  _getch ();
  Return 0;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions