M
M
mamadaliev2017-09-26 02:53:49
C++ / C#
mamadaliev, 2017-09-26 02:53:49

Selection sort in C++, why doesn't it work?

Hello! Who can explain why "selection sort" does not work correctly?
Input data:
756 -3245 534 -35 -533 536 0 353 5346 24 543
Output data:
-3245 -533 0 -35 24 536 534 353 5346 756 543
Code itself:

#include <iostream>
#include <cstdlib>

void selectSort(int A[], int n)
{
  for (int i = 0; i < n; i++)
  {
    int min = i;
    for (int j = i + i; j < n; j++)
    {
      if (A[j] < A[min]) min = j;
    }
    int temp = A[i];
    A[i] = A[min];
    A[min] = temp;
  }
}

int main()
{
  const int n = 11;
  int A[n];

  // Input
  std::cout << "Enter any " << n << " numbers:\n";
  for (int i = 0; i < n; i++) std::cin >> A[i];

  // Sorting
  selectSort(A, n);

  // Output
  std::cout << "\nSorted Array:\n";
  for (int i = 0; i < n; i++) std::cout << A[i] << " ";
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-09-26
@mamadaliev

You have a typo here: probably it should still be . for (int j = i + i;...i + 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question