bubble sort

 

 // 改进版,如果某一趟没有发生数据交换,那么数据已经有序了.
void
bubbleSort(int arr[], int n) { bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < n-j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }

 

 

// 普通冒泡排序
#include <stdio.h> #define SIZE 8 void bubble_sort(int a[], int n); void bubble_sort(int a[], int n) { int i, j, temp; for (j = 0; j < n - 1; j++) for (i = 0; i < n - 1 - j; i++) { if(a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } int main() { int number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12}; int i; bubble_sort(number, SIZE); for (i = 0; i < SIZE; i++) { printf("%d ", number[i]); } printf("\n"); }

 

posted @ 2016-08-18 07:03  PKICA  阅读(156)  评论(0编辑  收藏  举报