데이터 구조 몇 가지 교환 정렬

#include <iostream>

using namespace std;


void bubble_sort(int a[], int len)
{
	int i, j;
	int temp, flag = 1;
	for(i=0; i<len&&flag; i++)
	{
		flag = 0;
		for(j=0; j<len; j++)
		{
			if(a[i] < a[j])
			{
				flag = 1;
				temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
	}

	cout<<"    : ";
	for(i=0; i<len; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

void quick_sort(int a[], int left, int right)
{
	int temp;
	int i = left;
	int j = right;
	if(left < right)
	{	
		temp = a[left];
		while(i != j)
		{
			while(i<j&&a[j]>=temp)
				j--;
			if(i < j)
			{
				a[i] = a[j];
				i++;
			}
			while(i<j&&a[i]<=temp)
				i++;
			if(i < j)
			{
				a[j] = a[i];
				j--;
			}
		}
		a[i] = temp;      //
		quick_sort(a, left, i-1);
		quick_sort(a, i+1, right);
	}

	cout<<"    : ";
	for(i=0; i<9; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

void select_sort(int a[], int len)
{
	int i, j, k;
	int temp;
	for(i=0; i<len; i++)
	{
		k = i;
		for(j=i+1; j<len; j++)
			if(a[k] > a[j])
				k = j;
		if(i != k)
		{
			temp = a[i];
			a[i] = a[k];
			a[k] = temp;
		}
	}

	cout<<"      : ";
	for(i=0; i<9; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

int main(void)
{
	int a[] = {2,5,8,6,9,1,4,3,0};
	int len = sizeof(a)/sizeof(int);

	//    
//	bubble_sort(a, len);

	//    
//	quick_sort(a, 0, len-1);

	//    
	select_sort(a, len);
	return 0;
}

좋은 웹페이지 즐겨찾기