Skip to content

Instantly share code, notes, and snippets.

@tooshitaka
Last active March 17, 2017 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tooshitaka/c1902d7e49643e194b273bedb658dba3 to your computer and use it in GitHub Desktop.
Save tooshitaka/c1902d7e49643e194b273bedb658dba3 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int num_swap = 0;
// Selection sort
void selection_sort(int A[], int n)
{
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (A[j] < A[min])
min = j;
}
// Swap
if (min != i) {
num_swap++;
int tmp;
tmp = A[min];
A[min] = A[i];
A[i] = tmp;
}
}
}
int main(int argc, char** argv)
{
// Input
int n;
cin >> n;
int A[100];
for (int i = 0; i < n; i++)
cin >> A[i];
// Selection sort
selection_sort(A, n);
// Output
for (int i = 0; i < n; i++) {
if (i)
cout << " ";
cout << A[i];
}
cout << endl << num_swap << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment