////main.m//Mypritice1////Created by Laouhn on 15/7/18.//Copyright (c) 2015 Chi Hai Tao. All rights reserved.//#import<Foundation/Foundation.h>intMainintargcConst Char*argv[]) { /*int A[5] = {38,24,18,29,10}; Bubble Sort int temp = 0; for (int i = 0, i < 5-1; i++) {for (int j = 0; J < 5-1-I; + j) {if (A[j] > a[j + 1]) { temp = A[j]; A[J] = a[j+1]; A[j + 1] = temp; }}} for (int i = 0; i < 5; i++) {printf ("%d", a[i]); } */ //Bubble Sort Detailed /*1. Bubble sort principle//38,24,18,29,10//22 comparison, large front shift first cycle comparison 24,38,18,29,10 24,18,38,29,10 24,18,29,38,1 0 24,18,29,10,38 Second cycle comparison 18,24,29,10,38 18,24,29,10,38 18,24,10,29,38 third cycle comparison 18,24,10,29,38 18,10,24,29,38 Fourth cycle compare 10,18,24,29,38 each trip find the maximum value*/ inta[5] = { -, -, -, in,Ten}; inttemp =0; //The comparison of the first trip finds the maximum, note I < 5-1 cannot be crossed for I < 5 otherwise for(inti =0; I <5-1; i++ ) { if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } //Second trip comparison for(inti =0; I <5-1; i++ ) { if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } //Third trip comparison for(inti =0; I <5-1; i++ ) { if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } //Fourth trip comparison for(inti =0; I <5-1; i++ ) { if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } //as you can see from the above, the comparison code is the same.//5 numbers sorted, compared 4 times, n the number of sort comparison n-1 trip,//so in the For loop plus a for loop, which indicates the number of times the loop for(intj =0; J <5-1; J + +) {//It's been circulating 4 times. for(inti =0; I <5-1; i++) {//compared 4 times per trip. if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } } //each trip compares 4 times, according to the unnecessary comparison, the first trip compares 4 times, the second trip compares 3 times, the third trip compares 2, the fourth trip compares 1 times//The code above is a useless loop . for(intj =0; J <5-1; J + +) {//It's been circulating 4 times. for(inti =0; I <5-1-J; i++) {//Compare 5-1-j times per trip if(A[i] > a[i +1]) {temp=A[i]; A[i]= A[i +1]; A[i+1] =temp; } } } return 0;}
Bubble sort Detailed