Sort an array in ascending order

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.2 kB
0
Indexable
Never
#include <stdio.h>

void selectionSort (int a[], int n)
{
  int i, j, min;
  for (i = 0; i < n - 1; i++)
    {
      min = i;
      for (j = i + 1; j < n; j++)
	{
	  if (a[j] < a[min])
	    {
	      min = j;
	    }
	}
    
  int temp = a[min];
  a[min] = a[i];
  a[i] = temp;
    }
}

int binarySearch(int left, int right, int mid, int ele, int a[]) {
    while(right >= left) {
        int mid = (left + right) / 2;
        if(a[mid] == ele) {
            return mid;
        }
        if(a[mid] < ele){
            left = mid + 1;
    
        } else {
            right = mid - 1;
        }
    }
    return -1;
}


int main ()
{
    int n, i, ele;
    printf("Enter Number of elements \n");
    scanf("%d", &n);
    int a[n];
    printf("Enter elements of an array \n");
    for(i = 0; i < n; i++) {
        printf("Enter %d number:\t", i+1);
        scanf("%d", &a[i]);
    }
    selectionSort(a, n);
    printf("Sorted Array: \n");
    for(i =0; i<n; i++) {
        printf("%d \t", a[i]);
    }
    printf("\n");
    return 0;
}

/*
Enter Number of elements 
4
Enter elements of an array 
Enter 1 number: 23
Enter 2 number: 20
Enter 3 number: 19
Enter 4 number: 25
Sorted Array: 
19      20      23      25 
*/

Leave a Comment