- 思路:先排序,后去重
#include "stdio.h"
//快速排序
void quickSort(int arr[],int left, int right){
int ch[3] = {
0};
int tempLeft = left;
int tempRight = right;
//选取最左边的为基准元素
int temp = arr[left];
int compareRight = 1;
while (left != right) {
if (compareRight == 1) {
//temp和右边的数比
if(temp > arr[right]){
arr[left] = arr[right];
left++;
compareRight = 0;
}else{
right--;
}
}else{
//temp和左边的数比
if (temp < arr[left]) {
arr[right] = arr[left];
right--;
compareRight = 1;
}else{
left++;
}
}
}
arr[left] = temp;
//排序基准元素左边的
if (tempLeft < (left-1)) {
quickSort(arr, tempLeft, left-1);
}
//排序基准元素右边的
if (tempRight > left+1) {
quickSort(arr, left+1, tempRight);
}
}
//删除数组中的第几个元素
//len:数组长度
//index:要删除第几个元素
void arrDelete(int* arr,int index,int len){
for (int i = 0; i < len-1; i++) {
if (i < index) {
arr[i] = arr[i];
}else{
arr[i] = arr[i+1];
}
}
arr[len-1] = EOF;
}
//数组去重
void removeRepeat(int* arr,int len){
quickSort(arr, 0, len-1);
for (int i = 0; i < len-1; i++) {
if (arr[i] == arr[i+1]) {
arrDelete(arr, i, len);
len--;
i--;
}
}
}
int main()
{
int arr[5] = {
1,4,5,2,1};
printf("去重前---------------\n");
for (int i = 0; i < 5; i++) {
printf("%d\n",arr[i]);
}
removeRepeat(arr, 5);
printf("去重后---------------\n");
for (int i = 0; i < 5; i++) {
if (arr[i] == EOF) {
break;;
}
printf("%d\n",arr[i]);
}
}
打印结果:
去重前---------------
1
4
5
2
1
去重后---------------
1
2
4
5
Program ended with exit code: 0