排序100
Problem
protal:排序100
Description
Enter an array of length n to rank him in ascending order. that is, for any adjacent two number a[i], a[i+1], a[i] ≤ \leq ≤ a[i+1]
Standard Input
The first line is an integer n, which indicates the length of the array.
Next n lines, each line an integer a[i], indicating the contents of the array.
Standard Output
The first line of the Output indicates the length of the array.
The next n lines indicate the sort result.
Constraints
1 ≤ \leq ≤ n ≤ \leq ≤ 100
1 ≤ \leq ≤ a[ j ] ≤ \leq ≤ 109
Sample
Input
4
4
3
1
2
Output
4
1
2
3
4
Solution
Bubble Sort
pseudocode form Aizu OJ
BubbleSort(A)
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap A[j] and A[j-1]
cpp
#include <iostream>
using namespace std;
int main(void)
{
int n, a[100], i, j;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
int temp;
for (i = 0; i < n; i++)
{
for (j = n - 1; j > i; j--)
{
if (a[j] < a[j - 1])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
cout << n << endl;
for (i = 0; i < n; i++)
cout << a[i] << endl;
}
Insertion sort
pseudocode from wikipedia
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while
cpp
#include <iostream>
using namespace std;
int main(void)
{
int n, a[100], i, j, temp;
cin >> n;
cin >> a[0];
for (i = 1; i < n; i++)
{
cin >> temp;
for (j = i - 1; j >= 0; j--)
{
if (temp >= a[j])
{
a[j + 1] = temp;
break;
}
else
{
a[j + 1] = a[j];
continue;
}
}
if (j == -1)
a[0] = temp;
}
cout << n << endl;
for (i = 0; i < n; i++)
cout << a[i] << endl;
}
Section sort
pseudocode from Aizu OJ
SelectionSort(A)
for i = 0 to A.length-1
mini = i
for j = i to A.length-1
if A[j] < A[mini]
mini = j
swap A[i] and A[mini]
cpp
#include <iostream>
using namespace std;
int main(void)
{
int n, a[100], i, j;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
// Setion sort
int mini, temp;
for (i = 0; i < n; i++)
{
mini = i;
for (j = i; j < n; j++)
{
if (a[j] < a[