1.冒泡排序
代码:
#include<iostream>
using namespace std;
class List{
public:
List(){
array=NULL;
}
void creat(){
int n;
cout<<"请输入数组大小:";
cin>>n;
this->n=n;
array=new int[n];
for(int i=0;i<n;i++){
cin>>array[i];
}
}
void print(){
for(int i=0;i<n;i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
void sort(){
for(int i=1;i<n;i++){
int key=array[i];
int j=i-1;
while(array[j]>key&&j>=0){
array[j+1]=array[j];
j--;
}
array[j+1]=key;
}
}
private:
int *array;
int n;
};
int main(){
List l;
l.creat();
l.sort();
l.print();
}
2.快速排序
#include<iostream>
using namespace std;
class List{
public:
List(){
array=NULL;
}
void creat(){
int n;
cout<<"请输入数组大小:";
cin>>n;
this->n=n;
array=new int[n];
for(int i=0;i<n;i++){
cin>>array[i];
}
}
void print(){
for(int i=0;i<n;i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
void sort(){
sort(0,n-1);
}
private:
void sort(int lo,int hi){
if(lo>=hi){
return;
}
int i=lo;
int j=hi;
while(i<j){
while(array[i]<=array[j]&&i<j){
j--;
}
int t=array[i];
array[i]=array[j];
array[j]=t;
while(array[i]<=array[j]&&i<j){
i++;
}
t=array[i];
array[i]=array[j];
array[j]=t;
}
sort(lo,i-1);
sort(i+1,hi);
}
int *array;
int n;
};
int main(){
List l;
l.creat();
l.sort();
l.print();
}