一.选择排序
#include
//选择排序 //记录最小的那个数的索引值
//下面这个循环就是去寻找最小的那个数的index
//有比k对应的值更小的
//判断是否需要交换
//k和i对应的值交换
void selectsort(int array[],int counttimes){
int k = 0;
for (int i = 0; i < counttimes - 1; i++) {
int k = i ;
for (int j =i +1; j < counttimes; j ++) {
if (array[k] >array[j]) {
k = j ;
}
}
int temp;
if (k != i) {
temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
}
int main(int argc, const char * argv[]) {
int array[] = {1,25,8,22,2};
selectsort(array, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf(" ");
return 0;
}
二.快速排序
#include
void quicksort(int array[],int low,int high){
int i = low;
int j = high;
int temp = array[low];
if (low < high) {
while (i while (i < j&& array[j] >= temp) { j--; } array[i] = array[j]; while (i < j && array[i] <= temp) { i ++; } array[j] = array[i]; } array[i] = temp; quicksort(array,0,i-1); quicksort(array,i+1,high); } } int main(int argc,const char * argv[]){ int array[] = {3,1,9,2,8,3,7,4}; quicksort(array, 0, 7); for (int i = 0;i < 8;i++) { printf("%d ",array[i]); } printf("
"); return 0; } 三.直接排序 #include void insertsort(int array[],int elementNum){ int referenceNum = 0; for (int i = 1; i < elementNum; i ++) { referenceNum = array[i]; int j =i - 1; for (; j>= 0; j--) { if (array[j] > referenceNum) { array[j+1] = array[j]; }else{ break; } } if (j+1 != i ) { array[j+1] = referenceNum; } } } int main(int argc,const char * argv[]){ int array[] = {5,4,6,2,1}; insertsort(array, 5); for (int i = 0; i < 5; i ++) { printf("%d ",array[i]); } printf("
"); return 0; }