I am new to C and I'm practicing for-loops and pointers. In this exercise I try to write a function that sorts array elements. the first part of the code (where I input the elements) is working, but everything below gives me a hard time. I don't understand if the problem is in the if/else statements or anywhere else in the loop structure. also the last loop doesn't work (I just want it to iterate over the sorted array and print the elements, like I did before with it unsorted.
Hope I can get some help, and also if you see anything more that I should pay attention to...
Thanks a bunch.
I tried checking if the way I defined the loop was accurate, that I put all the right values and that the basic "idea" that I had for sorthing the array was ok.
void sort_array_elements()
{
int x, i, j, k, temp;
printf("\n input the number of elements to store in the array: ");
scanf_s("%d", &x);
int arrnum[30];
ptr_int = &x;
printf("input %d elements in the array: \n", x);
for (i = 0; i < x; i++)
{
scanf_s("%d\n", &arrnum[i]);
}
printf("the elements in the array before sorting: \n");
for (i = 0; i < x; i++)
{
printf("element %d: %d\n", i, arrnum[i]);
}
for (i = 0; i < x; i++)
{
for (j = 1; j < x; j++)
{
if (arrnum[i] > arrnum[j])
{
temp = arrnum[i];
arrnum[i] = arrnum[j];
arrnum[j] = temp;
}
else if (arrnum[i] == arrnum[j])
{
for (k = arrnum[i + 1]; k < x; k++)
{
if (arrnum[k] != arrnum[j])
{
temp = arrnum[k];
arrnum[k] = arrnum[j];
arrnum[j] = temp;
break;
}
}
}
}
}
printf("the elements in the array after sorting: \n");
for (i = 0; i < x; i++)
{
printf("element %d: %d\n", i, arrnum[i]);
}
}
Aucun commentaire:
Enregistrer un commentaire