冒泡排序算法代码
void vBubbleSort(int arr[], int len){int i, j, temp;for (j = 0; j < len - 1; j++){//每次最大元素就像气泡一样"浮"到数组的最后for (i = 0; i < len - 1 - j; i++){//依次比较相邻的两个元素,使较大的那个向后移if(arr[i] > arr[i + 1]){//交换两个数temp = arr[i];arr[i] = arr[i + 1];arr[i + 1] = temp;}}}}void vBubbleSortChange(int arr[], int len){int i,j,temp;int swapped = 1;for (j = 0; swapped; j++){//每次最大元素就像气泡一样"浮"到数组的最后swapped = 0;for (i = 0; i < len - 1 - j; i++){//依次比较相邻的两个元素,使较大的那个向后移if(arr[i] > arr[i + 1]){//交换两个数temp = arr[i];arr[i] = arr[i + 1];arr[i + 1] = temp;swapped = 1;}}//if(swapped == 0) {j = len-1;}//如果没有元素交换,说明序列是顺序的,退出循环}}void vCockTailSort(int arr[],int len){int tmp,i,left=0,right = len-1;while(left < right){for(i=left;i<right;i++){//正向冒泡,确定最大值if(arr[i]>arr[i+1]){tmp = arr[i];arr[i] = arr[i+1];arr[i+1] = tmp;}}right--;for(i=right;i>left;i--){//反向冒泡,确定最小值if(arr[i]<arr[i-1]){tmp = arr[i];arr[i] = arr[i-1];arr[i-1] = tmp;}}left++;}}void vCockTailSortChange(int arr[],int len){int tmp,i,left=0,right = len-1;int swapped = 1;int bound = 0;//记录某趟遍历的最后一次交换元素的位置,优化减少循环次数while(swapped){//如果没有元素交换,说明序列是顺序的swapped = 0;for(i=left;i<right;i++){//正向冒泡,确定最大值if(arr[i]>arr[i+1]){tmp = arr[i];arr[i] = arr[i+1];arr[i+1] = tmp;swapped = 1;bound = i;}}right=bound;//缩小遍历边界for(i=right;i>left;i--){//反向冒泡,确定最小值if(arr[i]<arr[i-1]){tmp = arr[i];arr[i] = arr[i-1];arr[i-1] = tmp;swapped = 1;bound = i;}}left=bound;//缩小遍历边界}}以上就是冒泡排序算法代码的详细内容,更多请关注小潘博客其它相关文章!