Thứ Bảy, 15 tháng 11, 2014

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


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

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

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

   if(jmin!=i)
    swap(a[jmin],a[i]);
   }
 }


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<<"Selection Sort: "<<endl;

 SelectionSort(a,n);

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


 getch();
 return 0;
}

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