C语言对数组从小到大排序去重
时间: 2023-06-08 14:04:29 浏览: 98
可以使用快速排序或归并排序对数组排序,然后依次遍历数组,将重复的元素删除即可。下面是示例代码:
``` c
#include <stdio.h>
void quick_sort(int arr[], int left, int right) {
if (left >= right) return;
int i = left, j = right, pivot = arr[left];
while (i < j) {
while (i < j && arr[j] >= pivot) j--;
arr[i] = arr[j];
while (i < j && arr[i] <= pivot) i++;
arr[j] = arr[i];
}
arr[i] = pivot;
quick_sort(arr, left, i - 1);
quick_sort(arr, i + 1, right);
}
void remove_duplicates(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
if (arr[i] == arr[i + 1]) {
for (int j = i + 1; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
size--;
i--;
}
}
}
int main() {
int arr[] = {1, 3, 5, 2, 4, 3, 2, 6, 5};
int size = sizeof(arr) / sizeof(arr[0]);
// sort the array
quick_sort(arr, 0, size - 1);
// remove duplicates
remove_duplicates(arr, size);
// print the result
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
阅读全文