感兴趣的小伙伴可以先看看我的这篇文章哦,打开看看,说不定能帮到你一些~~
6-1 快速排序
给一个无序表,使用快速排序算法对它进行排序。
函数接口定义:
int Partition(SqList &L,int low,int high);
void QuickSort(SqList &L, int low, int high);
其中L是待排序表,low和high是排序的区间。
裁判测试程序样例:
#include
using namespace std;
#define MAXSIZE 50
typedef int KeyType;
typedef struct
{ KeyType key;
} ElemType;
typedef struct
{ ElemType r[MAXSIZE+1];
int length;
} SqList;
void Create(SqList &L)
{ int i;
cin>>L.length;
for(i=1;i<=L.length;i++)
cin>>L.r[i].key;
}
void Output(SqList L)
{ int i;
for(i=1;i<=L.length;i++)
cout<<L.r[i].key<<" ";
cout<<endl;;
}
int Partition(SqList &L,int low,int high);
void QuickSort(SqList &L, int low, int high);
int main ()
{ SqList L; int low,high;
Create(L);
low=1; high=L.length;
QuickSort(L,low,high);
Output(L);
return 0;
}
/* 请在这里填写答案 */
输入样例:
在这里填写一组输入
5
3 1 9 5 7
输出样例:
1 3 5 7 9
输入样例:
在这里填写一组输入
5
0 -1 8 -1 2
输出样例:
-1 -1 0 2 8
代码:
int Partition(SqList &L,int low,int high) {
int x = L.r[low].key;
while (low < high){
while (low < high && L.r[high].key >= x) {
high--;
}
L.r[low].key = L.r[high].key;
while (low < high && L.r[low].key <= x) {
low++;
}
L.r[high].key = L.r[low].key;
}
L.r[low].key = x;
return low;
}
void QuickSort(SqList &L,int low,int high) {
if (low < high) {
int res = Partition(L,low,high);
QuickSort(L,low,res - 1);
QuickSort(L,res + 1,high);
}
}
6-2 冒泡排序
编程实现冒泡排序函数。void bubbleSort(int arr[], int n);。其中arr存放待排序的数据,n为数组长度(1≤n≤1000)。
函数接口定义如下:
/* 对长度为n的数组arr执行冒泡排序 */
void bubbleSort(int arr[], int n);
请实现bubbleSort函数,使排序后的数据从小到大排列。
裁判测试程序样例:
#include <stdio.h>
#define N 1000
int arr[N];
/* 对长度为n的数组arr执行冒泡排序 */
void bubbleSort(int arr[], int n);
/* 打印长度为n的数组arr */
void printArray(int arr[], int n);
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int main() {
int n, i;
scanf(“%d”, &n);
for (i = 0; i < n; ++i) {
scanf(“%d”, &arr[i]);
}
bubbleSort(arr, n);
printArray(arr, n);
return 0;
}
/* 打印长度为n的数组arr /
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf(“%d”, arr[i]);
if (i < n - 1) / 下标0…n-2每个元素后面有个空格 /
printf(" “); /下标n-1,也就是最后一个元素后面没有空格/
}
printf(”\n"); / 一行打印完后换行 */
}
/* 你的代码将嵌在这里 */
输入样例:
10
1 19 9 11 4 3 5 8 10 6
输出样例:
1 3 4 5 6 8 9 10 11 19
代码:
void bubbleSort(int arr[],int n) {
int i, j;
for (i = 0; i < n - 1; i++){
for (j = 0; j < n - i - 1; j++){
if (arr[j] > arr[j+1]){
swap(&arr[j],&arr[j + 1]);
}
}
}
}