Jumaat, Januari 10, 2014

C++ : Bubble sort

#include <iostream>
using namespace std;

void bubbleSort(int x[],int n);

int main()
{

    int x[]={2,6,5,3,7,4,1,8,9,5};

    // Display before sort
    cout<<"Before sort:\n";
    for(int i = 0; i < 10; i++) {
        cout << x[i] << " ";
    }

    // Sort the given array
    bubbleSort(x,10);

    // Display the sorted array
    cout<<"\n\nAfter sort:\n";
    for(int i = 0; i < 10; i++) {
        cout << x[i] << " ";
    }
}

void bubbleSort (int x[],int n) {
    int temp, flag = 1;

    while(flag) {
        flag = 0;

        for(int a = 0; a < (n - 1); a++) {
            if(x[a] > x[a + 1]) {
                flag = 1;

                temp = x[a];
                x[a] = x[a + 1];
                x[a + 1] = temp;
            }
        }
    }
}

Output:
Before sort:
2 6 5 3 7 4 1 8 9 5

After sort:
1 2 3 4 5 5 6 7 8 9

0 ulasan:

Catat Ulasan

Pesanan daripada penulis :
Selamat datang ke 0x2013LΣΣT. Sekiranya anda mempunyai persoalan, pandangan, permintaan, bantuan, cadangan dan sebagainya. Tinggalkan pesanan anda ke dalam kotak komen. Terima kasih !
- http://0x2013.blogspot.com -