Chủ Nhật, 23 tháng 11, 2014

Thuật toán sắp xếp BubbleSort



#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;

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

void BubbleSort(int a[], int n)
{
 for(int i=0; i<n-1;i++)
  for(int j=n-1;j>i;j--)
  {
   if(a[j]<a[j-1])
    swap(a[j],a[j-1]);
    }
}

main()
{
 int n=8;
 int a[]={1,5,3,4,9,7,3,4};

 for(int i=0;i<n;i++)
  cout<<a[i]<<"  ";

 cout<<endl<<"Bubble Sort: "<<endl;

 BubbleSort(a,n);
 for(int i=0;i<n;i++)
  cout<<a[i]<<"  ";

 getch();
 return 0;
}

Không có nhận xét nào: