I want to generate numbers from 1 to 10 in an array, then print them in descending order. The method I’ve used so far doesn’t work properly. Sometimes the number 10 is at the bottom, and all other numbers are correctly ordered.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a[7], j, i;
srand(time(NULL));
a[0] = rand() % 10;
int length = 7;
for(int i = 0; i < 7; i++) {
int duplikat = 0;
a[i] = rand() % 10+1;
for (int j=0; j<i; j++) {
// descending order: Just change (a[j] > a[j+1])
if(a[i] == a[j]) duplikat = 1;
if (a[j] < a[j+1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
if (duplikat) i--;
}
}
for(int i = 0; i< length; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
printf("\n");
for(j=0;j<7;j++) printf("\n%d ", a[j]);
return 0;
}
Some observations:
The line
if (duplikat) i--;should be outside the inner loop overj, so that you decreaseiat most once when a dupicate is found.Fiddling with the index of a
forloop to implement some skipping logic is also very brittle. Instead, consider awhileloop until your arrayais full where you add items only if they are no duplicates.If you want to "bubble down" the new number so that the part of the array is sorted, you must start from the right-hand side of the array. Otherwise, the only swap that may take place is of the new item with the last item in the array.
You could do something similar to insertion sort, where you keep the generated array sorted at all times:
Determine a new random number to add, the "pick".
Find the place
iwhere the pick goes; if the number was already generated, pick again.Otherwise, create an empty slot at the end of the array by incrementing the actual length, then move all elements right of the
ione place to the right. There is now a gap ati, where you place your pick.Repeat until your array has enough items.
In code: