一:选择排序和冒泡排序
这两种排序比较简单,直接贴出代码:
#include <stdio.h> void choose_sort(int *arr, int n);
void bubble_sort(int *arr, int n);
void show(int *arr, int n); int main()
{
int arr[] = {, , , , , , , , , }; /*选择排序*/
choose_sort(arr, );
show(arr, ); /*冒泡排序*/
bubble_sort(arr, );
show(arr, ); return ;
} void choose_sort(int *arr, int n)
{
int i = ;
int j = ;
int index = ;
int swap = ; for(i = ; i < n; i++) {
index = i;
for(j = i; j <n; j++ ) {
if(arr[index] > arr[j]) {
index = j;
}
}
swap = arr[i];
arr[i] = arr[index];
arr[index] = swap;
}
} void bubble_sort(int *arr, int n)
{
int i = ;
int j = ;
int swap = ; for(i = ; i < n - ; i++) {
for(j = ; j < n - i - ; j++) {
if(arr[j] > arr[j + ]) {
swap = arr[j];
arr[j] = arr[j + ];
arr[j + ] = swap;
}
}
}
} void show(int *arr, int n)
{
int i = ;
for(i = ; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
二:插入排序
下面代码是在一个有序数组中的插入一个数,插入后仍然有序:
#include <stdio.h> void insert_sort(int *arr, int num, int n); int main()
{
int arr[] = {, , , , , , , , };
insert_sort(arr, , ); int i = ;
for(i = ; i < ; i++) {
printf("%d ", arr[i]);
}
printf("\n"); return ;
} void insert_sort(int *arr, int num, int n)
{
int i = ;
int index = ; for(i = ; i < n; i++) {
if(arr[i] > num) {
index = i;
break;
}
} if(i == n) {
arr[i] = num;
}
else {
for(i = n; i >= index; i--) {
arr[i + ] = arr[i];
}
arr[index] = num;
}
}
三:快速排序
#include <stdio.h> void quick_sort(int *arr, int low, int high);
void show(int *arr, int n); int main()
{
int arr[] = {, , , , , , , }; quick_sort(arr, , );
show(arr, ); return ;
} void quick_sort(int *arr, int low, int high)
{
int pivot = ;
int i = ;
int j = ;
if(high <= low)
return; pivot = arr[low];
i = low;
j = high; while(i < j) {
while(i < j && arr[j] > pivot)
j--;
if(i < j)
arr[i++] = arr[j];
while(i < j && arr[i] < pivot)
i++;
if(i < j)
arr[j--] = arr[i];
}
arr[i] = pivot;
quick_sort(arr, low, i - );
quick_sort(arr, i + , high);
} void show(int *arr, int n)
{
int i = ;
for(i = ; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
快速排序涉及到递归调用,比较难理解,最好在纸上画出执行过程,慢慢理解