冒泡排序 选择排序 快速排序

/* Select Sorting */
void SelectSort(int A[]) {
int i=0, j=0, min=0;

for (i=0; i<MAX; i++) {
min = i;

for (j=i+1; j<MAX; j++) {
if (A[j] < A[min]) {
min = j;
}
}

if(i != min) {
Swap(&A[i], &A[min]);
}
}
}

/* Bubble sorting*/
void BubbleSort(int A[]) {
int i=0, j=0;
int last_swap = 0, last_swap_tmp = 0;

for(i = 0; i < MAX; i++) {
last_swap = last_swap_tmp;
for(j = MAX - 1; j > last_swap; j--) {
if(A[j] < A[j-1]) {
Swap(&A[j], &A[j-1]);
last_swap_tmp = j;
}
}

if(last_swap_tmp == last_swap) {
break;
}
}
}

2.左右两边分别向中间扫描；从右往左找到比Key小的值，填入左边的坑；从左往右找到比Key大的值，填入右边的坑；

3.当左右两边在中间交汇的时候，Key填入交汇处的坑

/* Quick Sorting */
void QuickSort(int A[], int low, int high) {
int left = low;
int right = high;
int key = A[left];

if(low >= high) return;

while(left < right) {

//右往左找小的
while(left < right && A[right] >= key) {
--right;
}
A[left] = A[right];

//左往右找大的
while(left < right && A[left] <= key) {
++left;
}
A[right] = A[left];
}

A[left] = key;
QuickSort(A, low, left-1);
QuickSort(A, right+1, high);
}

#include <iostream>

using namespace std;

#define MAX 20

void Swap(int* a, int* b) {
int tmp= *a;
*a = *b;
*b = tmp;
}

int main(int argc, char *argv[])
{
int A[MAX];

//freopen("input.txt", "r", stdin);

for(int i=0; i < MAX; i++) {
cin >> A[i];
}

fclose(stdin);

/* Select sorting */
//SelectSort(A);

/* bubble sorting */
//BubbleSort(A);

/* Quick sorting */
QuickSort(A, 0, ( sizeof(A)/sizeof(A[0]) ) -1 );

for(int i=0; i < MAX; i++) {
cout << A[i] << " ";
}
cout << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客