Output
5 8
8 9
9 6
6 4
4 7
7 0
0 0
0 1 2 3 4 5 6 7 8 9
Solution
#include <iostream>
using namespace std;
void sort_array(int a[], int len)
{
for(int i = 0; i < len; ){
if( a[i] != i){
int t = a[a[i]];
a[a[i]] = a[i];
a[i] = t;
cout << a[i] << " " << a[a[i]] << endl;
}
else{
i++;
}
}
}
int main(int argc, char* argv[])
{
int a[] = {3, 1, 2, 5, 7, 8, 4, 0, 9, 6};
sort_array(a, 10);
for(int i = 0; i < 10; i ++){
cout << a[i] << " ";
}
return 0;
}
Problem
Given an array containing (0..n-1) but in random order, you can only loop through the array once and use swap operation, please sort the array.