我需要编写一个程序,对给定的数组进行排序,使具有相同数字的数字位于前面。顺序必须保持不变。这将是一个大问题,但我不允许使用任何额外的数组、函数等。我真的不知道如何对数字进行排序以使顺序保持不变。而且数组最多包含 100 个元素。
示例:
输入: 1 22 43 444 51 16 7 8888 90 11
输出: 1,22,444,7,8888,11,43,51,16,90。
到目前为止我已经写了这个:
#include <stdio.h>
int main()
{
int a = 0, i = 0, niz[100], temp, N, j, logika, cifra1, cifra2, brojac = 0, brojac2 = 1;
printf("Unesite brojeve: \n");
do {
scanf("%d", &niz[i]);
if (niz[i] == -1) {
i--;
break;
}
i++;
} while (i < 100);
N = i;
for (i = 0; i < N; i++) {
a = niz[i];
logika = 1;
cifra1 = a % 10;
cifra2 = niz[i] / 10;
while (cifra2) {
if (cifra2 % 10 != cifra1) {
logika = 0;
break;
}
cifra2 = cifra2 / 10;
}
if (a / 10 == 0) logika = 1;
if (logika == 1) {
niz[brojac++] = niz[i];
}
if (logika == 0) {
niz[i] = temp;
niz[N - 1] = niz[i];
niz[N - i] = temp;
}
}
printf("Nakon preslaganja niz glasi: \n");
for (i = 0; i <= N; i++) {
if (i < N)
printf("%d,", niz[i]);
else {
printf("%d.", niz[i]);
}
}
return 0;
}
最佳答案
#include <stdio.h>
enum { MAX_NUMBERS = 100 };
int main(void)
{
int numbers[MAX_NUMBERS];
int numbers_count = 0;
int input;
puts("Please enter your numbers, end input with -1:");
while (numbers_count < MAX_NUMBERS && scanf(" %d", &input) == 1 && input != -1)
numbers[numbers_count++] = input;
int current_insertion_point = 0; // where to insert
for (int i = 0; i < numbers_count; ++i) {
int all_digits_the_same = 1;
// check if number only contains one probably repeated digit:
int current_number = numbers[i];
int last_digit = -1;
while (current_number && all_digits_the_same) {
int current_digit = current_number % 10;
current_number /= 10;
if (last_digit != -1 && current_digit != last_digit)
all_digits_the_same = 0;
last_digit = current_digit;
}
// insert the number:
if (all_digits_the_same) {
int temp = numbers[i];
// nove the range current_insertion_point ... i to the right
for (int k = i; k > current_insertion_point; --k)
numbers[k] = numbers[k - 1];
// so there is space to insert the number previously numbers[i]
numbers[current_insertion_point++] = temp;
}
}
for (int i = 0; i < numbers_count; ++i)
printf("%d ", numbers[i]);
putchar('\n');
}
输出:
Please enter your numbers, end input with -1:
1 22 43 444 51 16 7 8888 90 11 -1
1 22 444 7 8888 11 43 51 16 90
关于c - 排序数组C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439395/