array in descending order doesn't work in C -


      #include <stdio.h>        int main()        {         int a[100],i,n,j,p;         printf("enter number of elements:\n ");         scanf("%d",&n);         printf("enter array:\n");         for(i=0;i<n;i++)         {           scanf("%d",&a[i]);         }         for(i=0;i<n;i++)         {           for(j=1;j<n;j++)           {             if(a[i]>a[j])             {               p=a[j];               a[j]=a[i];               a[i]=p;             }           }         }         printf("the array looks :\n");         for(i=0;i<n;i++)         {           printf("%d\t",a[i]);         }           return 0;       } 

this works smooth except smallest element still first :( when run it has no errors, when enter numbers ex. 1,2,3,4,5 , turns out 1 5 4 3 2.

please more organized code!

here neater-looking version of it:

#include <stdio.h>  void swap(int* a, int* b) {     int t = *a;     *a = *b;     *b = t; }  void selectionsort(int a[], int n) {     int i, j;     (i = 0; < n; i++)         (j = + 1; j < n; j++)             if (a[i] > a[j])                 swap(&a[i], &a[j]); }  main() {     int n;     printf("enter number of elements: ");     scanf("%d", &n);      int a[n], i;     printf("enter array:\n");     (i = 0; < n; i++) scanf("%d", &a[i]);      selectionsort(a, n);      printf("the array looks this:\n");     (i = 0; < n; i++) printf("%d ", a[i]); } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -