【发布时间】:2019-08-24 12:50:15
【问题描述】:
我需要设计一种算法来对仅包含数字 -1,0,1 的数组进行排序,而不使用任何临时变量或数组并且仅使用交换我想出了以下方法我不确定如果是 O(n)。
#include <stdio.h>
#define MAXSIZE 10
int main()
{
int array[MAXSIZE];
int i, j, num = 8, temp;
int list[] = {-1,0,-1,0,1,1,0,1};
int size = sizeof(list)/sizeof(list[0]);
for (int i = 1; i < size; i++) {
if (list[i] < list[i - 1]) {
list[i] = list[i] + list[i - 1];
list[i - 1] = list[i] - list[i - 1];
list[i] = list[i] - list[i - 1];
i = 0;
}
}
printf("Sorted array is...\n");
for (int i = 0; i < size; i++)
{
printf("%d\n", list[i]);
}
}
【问题讨论】:
-
请注意,这不是冒泡排序,因为冒泡排序需要与所有后续元素进行比较,因此在运行时是二次的。
-
也许你只计算 -1、0 和 1 的数量。然后首先从 -1 开始重新生成每个正确数量的数组..
-
我不需要任何特定的算法我只需要验证我写的算法的复杂性