四种排序-笔记

顺序排序

1
2
3
4
5
6
7
8
9
10
11
12
13
int n = 10 ,temp;i
int a[] = { 1,2,4,5,6,21,12,7,10,31,3 };

for(int i=0;i<n-1;i++)
for (int j = i+1; j < n - 1; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

插入排序

1
2
3
4
5
6
7
8
9
10
11
12
13
int n = 10 ,j,temp;
int a[] = { 1,2,4,5,6,21,12,7,10,31,3 };
for (int i = 1; i < n; i++)
{
temp = a[i];
j = i;
while (j > 0 && a[j - 1] > temp)
{
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}

选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int n = 10 ,temp;
int a[] = { 1,2,4,5,6,21,12,7,10,31,3 };

for (int i = 0; i < n-1; i++)
{
int p = i;
for (int j = i + 1; j < n; j++)
{
if (a[p] > a[j])
{
p = j;
}
}
if (p != i)
{
temp = a[i];
a[i] = a[p];
a[p] = temp;
}
}

冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
int n = 10 ,temp;
int a[] = { 1,2,4,5,6,21,12,7,10,31,3 };

for(int i=0;i<n-1;i++)
for (int j = 0; j < n - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!