欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

归并排序、插入排序、冒泡排序、选择排序

程序员文章站 2022-05-12 16:38:20
...

#include
#include
#include
using namespace std;
void maopao(int intarr[], int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - i - 1; j++)
{
if (intarr[j] > intarr[j + 1])
{
int temp = intarr[j];
intarr[j] = intarr[j + 1];
intarr[j + 1] = temp;
}
}
}
}
void selecetSort(int intarr[], int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = i + 1; j < length; j++)
{
if (intarr[i] > intarr[j])
{
int temp = intarr[i];
intarr[i] = intarr[j];
intarr[j] = temp;
}
}
}
}
void insertSort(int intarr[], int length)
{
int start = 0;
int insert = 1;
while (insert < length)
{
int key = intarr[insert];
while (start >= 0 && intarr[start] > key)
{
intarr[start + 1] = intarr[start];
start–;
}
intarr[start + 1] = key;
start = start + 1;
insert= start+1;
}

}
void mergeArray(int intarr[], int start, int mid, int end)//0 5 9
{

int lengthArr = end - start+1;
int *arr = new int[lengthArr];
int start1 = start;
int start2 = mid + 1;
int i = 0;
while (start1 <= mid || start2 <= end)
{
	if (start1 <= mid && start2 <= end)
	{
		int key1 = intarr[start1];
		int key2 = intarr[start2];
		if (intarr[start1] > intarr[start2])
		{
			arr[i] = intarr[start1];
			i++;
			start1++;
		}
		else
		{
			arr[i] = intarr[start2];
			i++;
			start2++;
		}
	}
	else if (start1 <= mid)
	{
		arr[i] = intarr[start1];
		start1++;
		i++;
	}
	else
	{
		arr[i] = intarr[start2];
		start2++;
		i++;
	}
}
for (int ii = start; ii <= end; ii++)
{
	intarr[ii] = arr[ii - start];
}

}
void mergeSort(int intarr[], int start,int end)
{
if (start >= end)
{
return;
}
int mid = (start + end) / 2;
mergeSort(intarr, start, mid);
mergeSort(intarr, mid + 1, end);
mergeArray(intarr, start, mid, end);

}
void display(int intarr[],int length)
{
for (int i = 0; i < length; i++)
{
cout << intarr[i] << " ";
}
cout << endl;
}
int main()
{
const int num = 20;
int intarr[num];
srand((unsigned)time(NULL));
for (int i = 0; i < num; i++)
{
int val = rand() % 100;
intarr[i] = val;
}
display(intarr, num);
//int intarrtest[10] = { 0,2,4,6,8,1,3,5,7,9 };//0 4 9
//display(intarrtest, 10);
//mergeArray(intarrtest,0,4,9);
mergeSort(intarr, 0, num - 1);
display(intarr, num);
system(“pause”);
return 0;
}