I’m trying to write a code to let user write his own numbers and decide whether he wants them to be sorted in ascending or descending order, and order them with bubble sort. This is what I could write so far (aka the obvious entrance);
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, a, number;
printf("Enter your numbers. Write -1 to stop. \n");
do {
scanf("%d", &a);
} while(a != -1);
printf("Enter 1 if you want them to be in ascending order. Enter 2 if you want descending order\n");
scanf("%d", &a);
if(a = 1)
do {
system("PAUSE");
return 0;
}
My problem is, I really don’t know how to merge bubble sort to that. In all examples I could find had arrays which’ve been set before hand. I’m thinking I should start with a for structure but I’ve no idea.
EDIT:
I’ve came this far thanks to the helps, it kind of “works” until I write 1 or 2 then it crashes. Any suggestions?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int myarray[100],index,a,b,swap,turn;
index=0;
printf("Enter your numbers. Write -1 to stop. \n");
do{
scanf("%d", &myarray[index]);
index++;
}while(myarray[index-1] != -1);
printf("Enter 1 if you want them to be in ascending order. Enter 2 if you want descending order\n");
scanf("%d",&b);
if(b == 1) {
for(turn=1; turn <= myarray[100] -1; turn++)
for(index = 0; index <= myarray[100]; index++)
{
if (myarray[index] > myarray[index+1]){
swap = myarray[index];
myarray[index] = myarray[index+1];
myarray[index+1] = swap; }
}
}
else {
for(turn=1; turn <= myarray[100] -1; turn++)
for(index = 0; index <= myarray[100]; index++)
{
if (myarray[index] < myarray[index+1]){
swap = myarray[index];
myarray[index] = myarray[index+1];
myarray[index+1] = swap; }
}
}
system("PAUSE");
return 0;
}
1 Answer