Recently learned several sorts of sort, want to record down
(a) Bubble Sort:
#include <cstdio>
#include <cstring>
#define MAX 1001
Using namespace std;
int main ()
{
int a[max]={10,43,48,1,8,3,5,7,1,-21},t;
For (int I=0;i<10-1;i++)
For (int J=0;j<10-i-1;j++)//because the back J plus 1, so first minus 1
If (a[j]>a[j+1])//front number vs. subsequent number comparison size
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
For (int I=0;i<10;i++)
printf ("%d", a[i]);
Return 0;
}
Summary: bubbling sorting is a sort of time-space-changing method with a time complexity of O (n^2).
(b) Select Sort:
#include <cstdio>
#include <cstring>
#define MAX 1001
Using namespace std;
int main ()
{
int a[max]={10,43,48,1,8,3,5,7,1,-21},t,min;
For (int I=0;i<10-1;i++)
{
int index=i;
min=a[i];
For (int J=i+1;j<10;j++)
If (min>a[j])
{
min=a[j];
index=j;
}
t=a[i];
a[i]=min;
a[index]=t;
}
For (int I=0;i<10;i++)
printf ("%d", a[i]);
Return 0;
}
Summary: The average time complexity for selecting a sort is o (n^2).
Note: the above two sorting methods are rarely used because of the random complexity hit.
(iii) Quick Ordering:
#include <cstdio>
#include <cstring>
#define MAX 1001
Using namespace std;
void QSort (int left,int right,int *a)
{
If (left>right) return;
int i=left;
int j=right;
int key=a[left];
While (i<j)
{
While (i<j&&key<=a[j]) j--;
a[i]=a[j];
While (i<j&&key>=a[i]) i++;
a[j]=a[i];
}
a[i]=key;
QSort (left,i-1,a);
QSort (i+1,right,a);
}
int main ()
{
int a[max]={10,43,48,1,8,3,5,7,1,-21};
QSort (0,9,a);
For (int I=0;i<10;i++)
printf ("%d", a[i]);
Return 0;
}
Summary: the time complexity for quick sorting is O (N), which is one of my favorite sorting methods.
What is wrong with the above also hope that we learn together.
Summarize the commonly used sort