need help bubble sort

#include <iostream>

using std::cout;
using std::endl;

void bubble(int arr[], int size)
{
/* need help here */
}

void printlist(int arr[], int size)
{
for(int i = 0; i < size; i++)
cout << arr[i] << ", ";
cout << endl;
}

int main()
{
int list[] = {20, 56, 23, 2, 1, 90, 1002, 103, 342, 12};

cout << "Before: " << endl;
printlist(list, 10);
bubble(list, 10);

cout << "After: " << endl;
printlist(list, 10);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <iomanip>

void swap( int& a, int& b )
{
    const int temp = a ;
    a = b ;
    b = temp ;
}

void bubble_sort( int arr[], int size )
{
    bool swapped = false ;

    // for each element in the array, up to the last but one element
    for( int i = 0 ; i < size-1 ; ++i )
    {
        // if this element is greater than the next element
        if( arr[i] > arr[i+1] )
        {
            swap( arr[i], arr[i+1] ) ; // swap them
            swapped = true ; // set the flag to indicate that items were swapped
        }
    }

    if(swapped) // if at least one pair of items were swapped
        bubble_sort( arr, size ) ; // repeat the procedure till no more swaps are required
}

void print( const int arr[], int size )
{
    for( int i = 0 ; i < size ; ++i ) std::cout << std::setw(5) << arr[i] ;
    std::cout << '\n' ;
}

int main()
{
   int list[] = { 20, 56, 23, 2, 1, 90, 1002, 103, 342, 12 };
   const int size = sizeof(list) / sizeof( list[0] ) ;

   std::cout << "Before:\n" ;
   print( list, size );

   bubble_sort( list, size );

   std::cout << "After:\n" ;
   print( list, size );
}

http://coliru.stacked-crooked.com/a/820f3aaa60bfaae0
Topic archived. No new replies allowed.