发布网友 发布时间:2022-05-06 04:02
共1个回答
热心网友 时间:2023-10-03 08:01
#include<iostream>
using namespace std;
int a[8] ={56,34,78,26,9,67,12,36};
int b[8] ={56,34,78,26,9,67,12,36};
int c[8] ={56,34,78,26,9,67,12,36};
int insert_sort(int n)
{
int j,temp;
for(int i = 1;i < n; i++)
{
if(a[i] < a[i-1])
{
temp = a[i];j = i-1;
do{
a[j+1] = a[j];
j--;
}while(temp <= a[j]);
a[j+1] = temp;
}
for(int i = 0; i< n; i++)
cout<<a[i]<<ends;
cout<<endl;
}
return 0;
}
int bubbleSort(int n)
{
int i,j,t;
bool exchange;
for(j = 0; j<n-1; j++)
{
exchange = 0;
for(i = 0;i< n-j-1; i++)
if(b[i]>b[i+1])
{
t = b[i];
b[i] = b[i+1];
b[i+1] = t;
exchange = 1;
}
for(int i = 0; i< n; i++)
cout<<b[i]<<ends;
cout<<endl;
if(!exchange)
return 1;
}
return 0;
}
int selectSort(int n)
{
int i,j,k,temp;
for(i = 0; i< n-1; i++)
{
k = i;
for(j = i+1; j< n; j++)
{
if(c[k]>c[j])
k = j;
}
if(k!= i)
{
temp = c[i];
c[i] = c[k];
c[k] = temp;
}
for(int i = 0; i< n; i++)
cout<<c[i]<<ends;
cout<<endl;
}
return 0;
}
int main()
{
int n= 8;
cout<<"插入排序,每次(第一行是原来的序列):"<<endl;
for(int i = 0; i< n; i++)
cout<<a[i]<<ends;
cout<<endl;
insert_sort(n);
cout<<"最终结果:"<<endl;
for(int i = 0; i< n; i++)
cout<<a[i]<<ends;
cout<<endl<<endl;
cout<<"冒泡法,每次(第一行是原来的序列):"<<endl;
for(int i = 0; i< n; i++)
cout<<b[i]<<ends;
cout<<endl;
bubbleSort(8);
cout<<"最终结果:"<<endl;
for(int i = 0; i< n; i++)
cout<<b[i]<<ends;
cout<<endl<<endl;
cout<<"选择排序,每次(第一行是原来的序列):"<<endl;
for(int i = 0; i< n; i++)
cout<<c[i]<<ends;
cout<<endl;
selectSort(8);
cout<<"最终结果:"<<endl;
for(int i = 0; i< n; i++)
cout<<c[i]<<ends;
cout<<endl;
system("pause");
}