Skip to main content

Section 22.7 Practice: Bubble Sort

Check Your Understanding Check Your Understanding

1.

From where does "Bubble Sort" get its name?
  • Largest elements bubble gradually to the top
  • Correct
  • Named after Edgar D. Bubble
  • Not quite. Try again!
  • It was invented by the same person who invented gum
  • Not quite. Try again!
  • No reason
  • Not quite. Try again!

2.

Complete the following C program so that it correctly sorts the given array from smallest to largest using bubble sort. In particular, you need to complete the function bubbleSort() below which handles the sorting. Everything else has been done for you already.

Compile and run the code below in your own C environment.

#include <stdio.h>

void printArray(int numbers[], int len);
void bubbleSort(int numbers[], int len);
int main(void)
{
    /* Feel free to change the array, just be sure to update the length n, if necessary. */ 
    int numbers[]={5, -1, 8, 4, 0, -10, 12, 6};
    int n=8;
    int i, j;
    
    printf("Before: ");
    printArray(numbers, n);
    bubbleSort(numbers, n);
    printf("Sorted array: ");
    printArray(numbers, n);
    
    return(0);
}

void printArray(int numbers[], int len)
{
    int i;
    for (i=0; i<len; i++) 
    {
        printf("%d ", numbers[i]);
    }
    printf("\n");
}

void bubbleSort(int numbers[], int len)
{
    int i,j;
    
    for(j=0;j<len-1; j++)       
    {
        for(i=0;i<len-1;i++)
        {
            
            /* You need to fill in this part. 
               If you use additional variables,
               be sure to declare them. */
    
        }
    }
}
When your program performs correctly youโ€™ll be given a keyword to enter in Canvas.

3.

Suppose that you have made the following declarations:
int num[] = {5,3,7,9,2,4,6}; 
int index[] = {2,3,4,5,6,7,1};
What is index[3]? Choose one: 1 / 2 / 3 / 4 / 5
What is num[index[3]]? Choose one: 2 / 3 / 4 / 5 / 6 / 7 / 9
Feel free to use the window below to try out some code. Be sure to work the correct answer out "by hand" first before verifying your answer using the code window.

Compile and run the code below in your own C environment.

#include <stdio.h>

int main(void) {
   
   /* Try it out! */
      
   return(0);
}
Enter your two answers, separated by a comma, i.e. 8, 1