简体   繁体   中英

Bubble Sort not Sorting and extra elements

I am trying to make a bubble sort in descending order and I keep getting a weird output. When I am inputting the elements in the array, for element 1 it asks me for element 1 more than once, and it causes an extra element to be taken in and another thing is that the final element is not included in the array at all, which I am not understanding. This is the output of my full program, and my code is under it:

Input:

How many elements in your array?: 4
Enter elements in your array: 
Element 0: 
97
32
Element 1: 
13
Element 2: 
22
Element 3: 
244
Element 0: 32
Element 1: 13
Element 2: 22
Element 3: 0

My code:

#include <stdio.h>

void sort(int array[], int n);

int main() {

    int num = 0;
    printf("How many elements in your array?: ");
    scanf("%d",&num);
    while(num > 9)
        {
        printf("Only enter an array that is size 9 or less.\n");
        printf("Enter a new number: ");
        scanf("%d", &num);
        }
    int array[num];
    printf("Enter elements in your array: \n");
    for(int i = 0; i < num; i++)
    {   
        printf("Element %d: \n",i);
        scanf("%d ",&array[i]);
    }
    sort(array, num);
    for(int j = 0; j < num; j++)
    {
        printf("Element %d: %d\n", j, array[j] );

    }
    return 0;
}

void sort(int array[], int size)
{
    int temp;
    for(int i = 0; i < size; i++)
    {
        /*if(array[i] > array[i+1]) // smallest to biggest
        {
            *temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;

        }*/
        if(array[i] > array[i+1]) // 1 2
        {
            temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;
        }
    }
}

In addition to the comments, your " bubble sort " will never sort, because it isn't a bubble sort . A bubble sort implementation for your variables would be similar to:

int i, j, swap;

for (i = 0; i < size - 1; i++) {
    for (j = 0; j < size - i - 1; j++) {
        if (array[j] > array[j + 1]) {  /* For decreasing order use < */
            swap = array[j];
            array[j] = array[j + 1];
            array[j + 1] = swap;
        }
    }
}

That being said, your use of scanf is full of pitfalls. You Must validate the return of scanf to determine (1) Did the user cancel input by generating a manual EOF using Ctrl+d (or Ctrl+z on windoze)?; (2) Was there an input or matching failure that resulted in no conversion taking place?; and (3) If the conversion succeeded, is the value within the acceptable range? In your case that would take the form of:

    int num = 0,
        rtn;
    for (;;) {  /* loop continually until valid input received */
        printf ("\nHow many elements in your array?: ");
        rtn = scanf ("%d", &num);
        if (rtn == EOF) {
            fprintf (stderr, "user canceled input.\n");
            return 1;
        }
        else if (rtn == 0) {
            int c;
            fprintf (stderr, "error: invalid input.\n");
            /* discard any characters that remain after input failure */
            for (c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
        }
        else if (num > 9) {
            fprintf (stderr, "error: elements must be 9 or less.\n");
        }
        else
            break;
    }

( note: after an input failure, you must discard any characters that remain in stdin , otherwise, on the next iteration, your conversion will fail again leading to an infinite loop -- one of the primary pitfalls with using scanf for user input)

You can use an abbreviate check for the array values (rather than loop until you get correct input, you are just bailing, which eliminates discarding characters, etc.). However, there is no reason you cannot implement a fully robust solution in that loop, (implementing the full check and looping until all array elements are filled or the user cancels input).

    printf("\nEnter elements in your array: \n");
    for (int i = 0; i < num; i++) {   
        printf("Element[%2d]: ", i);
        if (scanf("%d",&array[i]) != 1) {
            fprintf (stderr, "error: invalid input.\n");
            return 1;
        }
    }

Putting all the pieces together, you could do something similar to the following:

#include <stdio.h>

void sort(int *array, int size);

int main (void) {

    int num = 0,
        rtn;
    for (;;) {  /* loop continually until valid input received */
        printf ("\nHow many elements in your array?: ");
        rtn = scanf ("%d", &num);
        if (rtn == EOF) {
            fprintf (stderr, "user canceled input.\n");
            return 1;
        }
        else if (rtn == 0) {
            int c;
            fprintf (stderr, "error: invalid input.\n");
            for (c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
        }
        else if (num > 9) {
            fprintf (stderr, "error: elements must be 9 or less.\n");
        }
        else
            break;
    }

    int array[num];     /* VLA for array */

    printf("\nEnter elements in your array: \n");
    for (int i = 0; i < num; i++) {   
        printf("Element[%2d]: ", i);
        if (scanf("%d",&array[i]) != 1) {
            fprintf (stderr, "error: invalid input.\n");
            return 1;
        }
    }

    sort (array, num);

    putchar ('\n');
    for(int j = 0; j < num; j++)
        printf("Element %d: %d\n", j, array[j]);

    return 0;
}

void sort(int *array, int size)
{
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (array[j] > array[j + 1]) {  /* For decreasing order use < */
                int swap = array[j];
                array[j] = array[j + 1];
                array[j + 1] = swap;
            }
        }
    }
}

Example Use/Output

$ ./bin/bubblesort_input

How many elements in your array?: twenty
error: invalid input.

How many elements in your array?: 12
error: elements must be 9 or less.

How many elements in your array?: 6

Enter elements in your array:
Element[ 0]: 12
Element[ 1]: 2
Element[ 2]: -12
Element[ 3]: -4
Element[ 4]: 5
Element[ 5]: 1

Element 0: -12
Element 1: -4
Element 2: 1
Element 3: 2
Element 4: 5
Element 5: 12

Look things over and let me know if you have any further questions.

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