You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
一、直接插入排序
(一)直接插入排序是把新的数据插入以及排序好的数列中,排序的基本方法是:每一步将一个待排序的元素,按其排序码的大小,插入到前面已经排好序的一组元素的适当位置上去,直到元素全部插入为止。
(二)代码:
#include<iostream>
using namespace std;
void insert_sort(int a[],int n) {
int i,j;
for(i=1; i<n; i++) { //循环从第2个元素开始
if(a[i]<a[i-1]) {
int temp=a[i];
for(j=i-1; j>=0 && a[j]>temp; j--) {
a[j+1]=a[j];
}
a[j+1]=temp;//此处就是a[j+1]=temp;
}
}
}
int main() {
int a[8]= {70,50,30,20,10,70,40,60};
int n=7;
insert_sort(a,n);
for(int i=0; i<=n; i++) {
cout<<a[i]<<' ';
}
return 0;
}
( 三) 时间复杂度: 直接插入排序的平均时间复杂度为O(n^2)。
( 四) 运行时间结果: 10000个数据的运行时间为239ms。
二、折半插入排序
(一)插入排序,就是不断的依次将元素插入前面已排好序的序列中。
(二)代码:
void BinaryInsertSort(SeqList &L){
int i,j,low,high,mid;
for(i=2; i<L.n; i++){
L.data[0] = L.data[i];
low=1;
high = i-1;
while(low<=high){
mid = (low+high)/2;
if(L.data[0]<L.data[mid]) high=mid-1;
else low=mid+1;
}
for(j=i-1; j>=high+1; j--){
L.data[j+1] = L.data[j];
}
L.data[high+1] = L.data[0];
}
}
(三)时间复杂度:折半插入排序的时间复杂度仍为 O(n^2)。
( 四) 运行时间: 0.283秒
三、冒泡排序
(一)代码:
#include<stdio.h>
void main()
{
int n[10] = { 25,35,68,79,21,13,98,7,16,62 };
int i, j,k,temp;
for (i = 1; i <= 9; i++)
{
for (j = 0; j <= 9 - i; j++)
{
if (n[j] > n[j + 1])
{
temp = n[j];
n[j] = n[j + 1];
n[j + 1] = temp;
}
}
printf("第%d趟排序完成后的数据排序:\n",i);
for (k = 0;k < 10; k++)
printf("%-4d", n[i]);
printf("\n");
}
printf("排序过后的数顺序:\n");
for (i = 0; i < 10; i++)
printf("%-4d", n[i]);
}
( 二) 时间复杂度: 冒泡排序平均时间复杂度为O(n2) 。
( 三) 运行时间: 0.463秒