排序算法C语言实现(一):选择排序, 冒泡排序, 插入排序

1 选择排序

#include <stdio.h>
//交换两个数

void
swap(int* a,int* b){ if(a != b){ *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } } //从大到小排序 //pSortArray为需要排序的数组,size为数组中元素的个数 void swapSort(int* pSortArray, int size) { int iMax; int iMaxIndex; for(int i = 0;i < size-1;i++){ iMaxIndex = i; for(int j = i + 1;j < size;j++){ if(pSortArray[iMaxIndex] < pSortArray[j])iMaxIndex = j; //找出未排序部分最大数的下标 } swap(pSortArray + iMaxIndex,pSortArray + i); } } void main() { int a[5] = {1,3,5,2,4}; swapSort(a,5); for(int i = 0;i < 5;i++)printf("%d ",a[i]); // 输出: 5 4 3 2 1 }

2 冒泡排序

#include <stdio.h>
//
交换两个数 void swap(int* a,int* b){   if(a != b){   *a = *a ^ *b;   *b = *a ^ *b;   *a = *a ^ *b;   } } //从大到小排序 //pSortArray为需要排序的数组,size为数组中元素的个数 void bubbleSort(int* pSortArray, int size) {   for(int i = 0;i < size-1;i++){     for(int j = size - 1;j >= i + 1;j--){       if(pSortArray[j-1] < pSortArray[j])swap(pSortArray + j,pSortArray+j-1);//将较大数往前移动     }   } } void main() {   int a[5] = {1,3,5,2,4};   bubbleSort(a,5);   for(int i = 0;i < 5;i++)printf("%d ",a[i]); // 输出: 5 4 3 2 1 }

3 插入排序

#include <stdio.h>
//
从大到小排序 //pSortArray为需要排序的数组,size为数组中元素的个数 void insertSort(int* pSortArray, int size) {   int iTemp;   int j;   for(int i = 1;i < size;i++){     iTemp = pSortArray[i];     for(j = i - 1;(j >=0) && (pSortArray[j] < iTemp);j--) pSortArray[j + 1]=pSortArray[j];     pSortArray[j + 1] = iTemp;   } } void main() {   int a[5] = {1,3,5,2,4};   insertSort(a,5);   for(int i = 0;i < 5;i++)printf("%d ",a[i]); // 输出: 5 4 3 2 1 }

猜你喜欢

转载自www.cnblogs.com/LiuJiandong/p/10683528.html