Thread: Array help
View Single Post
Old 10-26-2005, 08:34 AM   #5 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,726
redhead is on a distinguished road
For the second program:
take a look at this:
Code:
#include <stdio.h>
#define NUMBERS 10

int numbers[NUMBERS];

int sort(int ascending);

int main()
{
  int i;
  char ch;
  while(1){
    printf("Please select sort order the array\n");
    printf(" 1) Fill in array\n");
    printf(" 2) sort Ascending\n");
    printf(" 3) sort DEscending\n");
    printf(" q) quit\n");
    printf("Selection: ");
    fflush(stdout);
    ch = getchar();
    if(ch == 'q' || ch == 'Q')
      break; /* we quit from here */
    switch(ch)
      {
      case '1':
	for (i=0; i < NUMBERS; ++i) {
	  printf("\nEnter number %d: ", i+1);
	  scanf("%d", &numbers[i]);
	}
	ch=getchar();
	break;
      case '2':
	sort(1);
	break;
      case '3':
	sort(0);
	break;
      default:
	printf("Unsupported choice: %c\n", ch);
      }
    for(i=0; i < NUMBERS; ++i)
      printf("%d%c ", numbers[i], (i+1)%NUMBERS?',':'\n');
    printf("\n");
  }

  return(0);
}


int sort(int ascending)
{
  int i, j, tmp;
  for(i=NUMBERS-2; i >=0; i--)
    {
      tmp=numbers[i];
      if(ascending)
	for(j=i+1; j<=NUMBERS-1 && tmp > numbers[j]; ++j)
	  numbers[j-1]=numbers[j];
      else
	for(j=i+1; j<=NUMBERS-1 && tmp < numbers[j]; ++j)
	  numbers[j-1]=numbers[j];	
      numbers[j-1] = tmp;
    }
  return 0;
}
Bubblesort might be a bit too advanced at this point, so mine uses a lineary sort algorithm..
*Cough* the worst kind..
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote