|
|
#include <iostream>
using namespace std;
void swap(int&, int&);
bool larger(int a, int b);
bool smaller(int a, int b);
void sort(int*, int, bool (*compare)(int, int));
void swap(int &a, int &b) {
int t = a;
a = b;
b = t;
}
bool larger(int a, int b) {
return a > b;
}
bool smaller(int a, int b) {
return a < b;
}
void sort(int* arr, int length, bool (*compare)(int, int)) {
int flag = 1;
for(int i = 0; i < length-1 && flag == 1; i++) {
flag = 0;
for(int j = 0; j < length-i-1; j++) {
if(compare(arr[j+1], arr[j])) {
cout << "{";
for(int k = 0; k < 5; k++) {
cout << arr[k] ;
if (k<4){
cout << ", ";
}
}
cout << "} ";
cout << "j in " << j <<" swap : "<< "(" << arr[j+1] << "," << arr[j] << ")" << endl;
swap(arr[j+1], arr[j]);
flag = 1;
}//if
}//for
}//for
}
int main() {
int number1[] = {3, 5, 1, 6, 9};
cout << "sort {3, 5, 1, 6, 9}" << endl;
sort(number1, 5, larger);
cout << "大的在前 ";
for(int i = 0; i < 5; i++) {
cout << number1[i] << " ";
}
cout << endl;
int number2[] = {3, 5, 1, 6, 9};
cout << "sort {3, 5, 1, 6, 9}" << endl;
sort(number2, 5, smaller);
cout << "小的在前 ";
for(int i = 0; i < 5; i++) {
cout << number2[i] << " ";
}
cout << endl;
return 0;
}
|
Output:
|
|
sort {3, 5, 1, 6, 9}
{3, 5, 1, 6, 9} j in 0 swap : (5,3)
{5, 3, 1, 6, 9} j in 2 swap : (6,1)
{5, 3, 6, 1, 9} j in 3 swap : (9,1)
{5, 3, 6, 9, 1} j in 1 swap : (6,3)
{5, 6, 3, 9, 1} j in 2 swap : (9,3)
{5, 6, 9, 3, 1} j in 0 swap : (6,5)
{6, 5, 9, 3, 1} j in 1 swap : (9,5)
{6, 9, 5, 3, 1} j in 0 swap : (9,6)
大的在前 9 6 5 3 1
sort {3, 5, 1, 6, 9}
{3, 5, 1, 6, 9} j in 1 swap : (1,5)
{3, 1, 5, 6, 9} j in 0 swap : (1,3)
小的在前 1 3 5 6 9
|
|