Home  >  Article  >  php教程  >  Sorting bubble sort

Sorting bubble sort

高洛峰
高洛峰Original
2016-12-19 13:20:341100browse

The basic concept of Bubble Sort is: compare two adjacent numbers in sequence, put the decimal in the front and the large number in the back. That is, in the first pass: first compare the first and second numbers, put the decimal first and the large number last. Then compare the second number and the third number, put the decimal in front and the large number in the back, and continue like this until comparing the last two numbers, put the decimal in front and the large number in the back. This is the end of the first trip, leaving the largest number at the end. In the second pass: still start the comparison from the first pair of numbers (because it may be due to the exchange of the second number and the third number that the first number is no longer smaller than the second number), put the decimal first, and the large number After placing it, the comparison is continued until the second to last number (the first to last position is already the largest). At the end of the second pass, a new maximum number is obtained at the second to last position (in fact, it is the highest number in the entire sequence). The second largest number). Continue like this and repeat the above process until the sorting is finally completed.

c code is implemented as follows:

#include <stdio.h>  
  
//打印数组  
void display(int array[],int size){  
    printf("the array is:");  
    int i;  
    for(i=0;i<size;i++){  
        printf("%d ",array[i]);  
    }  
    printf("\n");  
}  
  
//冒泡排序算法  
void sort(int array[],int size){  
    int i,j,temp,flag;  
    for(i=0;i<size;i++){  
        flag = 0;  
        for(j=size-1;j>i;j--){  
            //如果前一个数大于后一个数,则交换  
            if(array[j-1]>array[j]){  
                temp = array[j];  
                array[j] = array[j-1];  
                array[j-1] = temp;  
                flag = 1;  
            }  
        }  
        //如果本次排序没有进行一次交换,则break,减少了执行之间。  
        if(flag == 0){  
            break;  
        }  
        display(array,size);  
    }  
}  
  
int main(void){  
    int array[10]={34,45,1,39,21,68,65,100,4,51};  
    display(array,10);  
    sort(array,10);  
    return 0;  
}



For more articles related to sorting and bubble sorting, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Bubble SortNext article:Bubble Sort