Bubble Sort C++

Pengertian bubble sort

Metode bubble sort adalah metode yang mendasarkan penukaran 2 buah elemen untuk mencapai keadaan terurut yang diinginkan.

Berikut ini contoh coding untuk bubble sort pada C++ :

#include
#include
using namespace std;
void cetak(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<length;i++)
cout<<array[i] << " " ;
cout << endl;
}

void bubbleSort(int *array,int length)//Bubble sort function
{
int i,j;
for(i=0;i<length;i++)
{
for(j=0;j<i;j++)
{
if(array[i] < array[j])
{
int temp=array[i]; //swap
array[i]=array[j];
array[j]=temp;
}

}
}
}

int main()
{

int a[]={9,6,5,23,2,66,14,8,2,7,1,8}; // array to sort
cetak(a,12); // print elements
bubbleSort(a,12); //call to bubble sort
cetak(a,12); // print elements
return 0;
}

Selamat berexplore kawanπŸ˜€

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s