冒泡排序法
1.比较相邻元素,如果第一个比第二个大,就交换
2.对每一对相邻元素做同样工作,执行完毕后找到第一个最大值
3.重复上述步骤,每次比较次数-1,直到不需要比较
#includeusing namespace std; int main() { int arr[] = { 56,37,9,2,85,5,54,50,26 }; cout << "排序前" << endl; for (int i = 0; i < 8; i++) { cout << arr[i] << " "; } cout << endl; //开始冒泡排序 for (int i = 0; i < 8 - 1; i++) //排序总轮数 = 元素个数 - 1 { //内层循环对比 for (int j = 0; j < 8-1-i; j++) //每轮对比次数 = 元素个数 - 排序轮数 - 1 { //若第一个数字比第二个数字大,则交换 if (arr[j]>arr[j+1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } //输出排序后结果 cout << "排序后" << endl; for (int i = 0; i < 8; i++) { cout << arr[i] << " "; } cout << endl; system("pause"); return 0; }
运行结果如下:



