简体   繁体   中英

Using Bubble sorting to an array of 5 numbers in C

I need to sort an array of 5 numbers, this is what I have. I prompt for input, then use bubble sorting to sort the date, and then print the array. However when I run the program the output is not sorted and isn't even the same as the input.

void main() {
    printf("Please enter five integers:\n");
    printf("First Number\n");
    scanf("%d", &numArray[0]);
    printf("Second Number\n");
    scanf("%d", &numArray[1]);
    printf("Third Number\n");
    scanf("%d", &numArray[2]);
    printf("Fourth Number\n");
    scanf("%d", &numArray[3]);
    printf("Fifth Number\n");
    scanf("%d", &numArray[4]);

    for (j=0; j<=5; ++j) {
        if (numArray[j] > numArray[j+1]) {
            temp = numArray[j];
            numArray[j] = numArray[j+1];
            numArray[j+1] = temp;
        }
    }

    for(int j = 0; j < 5; j++) {
        printf("%d ", numArray[j]);
    }
}

Your loop is invalid (it goes off the end by one), and your sort only contains one loop; a bubble sort contains two loops:

for (i = 0; i < SIZE-1; i++) {
    for (j = i+1; j < SIZE; j++) {
        if (val[i] > val[j]) swap(...);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM