8. Primary bubble sort series

Bubble Sort

Problem Description

Of N integers (data input from the keyboard) in ascending order

problem analysis

Comparing bubble sort is exchanged between two adjacent elements of a process into an ordered list of unordered list

Thought: onward scanning array from the header, by comparing the size of two adjacent elements in the scanning process

If two elements are adjacent, larger than the previous element behind the element, they are interchangeable, called

Erasing a reverse, during the scanning process, to keep the two adjacent elements is greater backward movement, will finally

The greatest change in the array to the end, which is the largest element in the array table rightful place, and then, the rest of the

Array elements (n-1 element) repeat the above process, the next smallest element into the penultimate position. Repeating the above process

Until the rest of the array elements to zero, at which point it becomes an ordered array

Suppose the number of array elements is n, the total number of comparison needed in the worst case is: ((n-1) + (n-2) + .... + 2 + 1) = n (n-1) /2

algorithm design

Double loop, a first control loop layer rounds the exchange, a second layer of control cycles round number to be exchanged

/* !< use c */
#include <stdio.h>

#define N 3    /* !< 数组大小改变时只需要改变N对应的值不需要改动程序 */

int main(void)
{
    int i, j, a[N], t, count = 0;
    printf("为数组元素赋初值:\n");
    for (i = 0; i < N; i++) {
        scanf("%d", &a[i]);
    }
    for (i = 1; i <= N-1; i++) {        /* !<控制比较的轮数 */
        for (j = 0; j < N-i; j++) {     /* !<控制每轮比较的次数 */
            if (a[j] > a[j+1]) {        /* !<数组相邻两个元素进行交换 */
                t = a[j];
                a[j] = a[j+1];
                a[j+1] = t;
            }
        }
    }

    printf("经过交换后的数组元素为:\n");
    for (i = 0; i  < N; i++) {
        count++;
        printf("%d ", a[i]);
        if (count % 5 == 0) {       //控制每行输出5个数
            printf("\n");
        }
    }
    printf("\n");
}

Guess you like

Origin www.cnblogs.com/xuzhaoping/p/11484525.html