C:(100分)(原理的话用文字不好描述,建议上B站看看动画演示)
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int arr[100001] = { 0 };
void myswap(int i, int j)
{
int a;
a = arr[i];
arr[i] = arr[j];
arr[j] = a;
}
void mysort(int x, int y)
{
int i = x;
int j = y;
int k = arr[(x + y) / 2];
while (i <= j)
{
while (arr[j] > k)
{
j--;
}
while (arr[i] < k)
{
i++;
}
if (i <= j)
{
myswap(i, j);
i++;
j--;
}
}
if (x < j)
{
mysort(x, j);
}
if (y > i)
{
mysort(i, y);
}
return;
}
int main()
{
int n = 0;
int i = 1;
scanf("%d", &n);
while (scanf("%d", &arr[i]) != EOF && getchar() != '\n')
{
i++;
}
mysort(1, n);
for (int j = 1; j <= n; j++)
{
printf("%d ", arr[j]);
}
return 0;
}
C++:(100分)
相较于C只是修改了一下输入和输出的部分
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
int arr[100001] = { 0 };
void myswap(int i, int j)
{
int a;
a = arr[i];
arr[i] = arr[j];
arr[j] = a;
}
void mysort(int x, int y)
{
int i = x;
int j = y;
int k = arr[(x + y) / 2];
while (i <= j)
{
while (arr[j] > k)
{
j--;
}
while (arr[i] < k)
{
i++;
}
if (i <= j)
{
myswap(i, j);
i++;
j--;
}
}
if (x < j)
{
mysort(x, j);
}
if (y > i)
{
mysort(i, y);
}
return;
}
int main()
{
int n = 0;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
}
mysort(1, n);
for (int j = 1; j <= n; j++)
{
cout << arr[j] << " ";
}
return 0;
}
python:(100分)
相较于C只是把C的部分python化
def mysort(x, y):
i = x
j = y
k = arr[(x + y) // 2]
while i <= j:
while arr[j] > k:
j -= 1
while arr[i] < k:
i += 1
if i<= j:
c = arr[i]
arr[i] = arr[j]
arr[j] = c
j -= 1
i += 1
if x < j:
mysort(x, j)
if y > j:
mysort(i, y)
n = eval(input())
arr = list(map(int,input().split(" ")))
mysort(0, n - 1)
for i in range(n):
print(arr[i], end = " ")