C - Array Array Sorting

Introduction

Suppose that you're sorting an array so that the smallest values are listed first.

If array[2] contains the value 20, and array[3] contains the value 5, these two elements would need to swap values.

To make it happen, you use a temporary variable in a series of statements that looks like this:

temp=array[2];       /* Save 20 in temp */ 
array[2]=array[3];   /* Store 5 in array[2] */ 
array[3]=temp;       /* Put 20 in array[3] */ 

In a bubble sort, each array element is compared with every other array element in an sequence.

When one value is larger (or smaller) than another, the values are swapped.

Otherwise, the comparison continues, loop through every possible permutation of comparisons in the array.

The following code shows how to implement A Bubble Sort.

Demo

#include <stdio.h> 

#define SIZE 10 //from w w  w. j  av a2  s .c o  m

int main() 
 { 
    int bubble[] = { 95, 60, 6, 87, 50, 24 , 0 ,100, 120}; 
    int inner,outer,temp,x; 

/* Display original array */ 
    puts("Original Array:"); 
    for(x=0;x<SIZE;x++) 
        printf("%d\t",bubble[x]); 
    putchar('\n'); 

/* Bubble sort */ 
    for(outer=0;outer<SIZE-1;outer++) 
    { 
        for(inner=outer+1;inner<SIZE;inner++) 
        { 
            if(bubble[outer] > bubble[inner]) 
            { 
                temp=bubble[outer]; 
                bubble[outer] = bubble[inner]; 
                bubble[inner] = temp; 
            } 
        } 
    } 

/* Display sorted array */ 
    puts("Sorted Array:"); 
    for(x=0;x<SIZE;x++) 
        printf("%d\t",bubble[x]); 
    putchar('\n'); 

    return(0); 
 }

Result

The code above has three parts, each headed by a comment:

  • display the original array.
  • sort the array.
  • display the sorted array

The constant SIZE is defined.

The sort itself involves nested for loops: an outer loop and an inner loop.

The outer loop marches through the entire array, one step at a time.

The inner loop takes its position one element higher in the array and swoops through each value individually.

Related Topics

Exercise