Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Thursday, March 2, 2017

Selection Sort in C language

Selection Sort

This is a one kind of sorting technique. The complexity of this sorting technique is,
Worst-case performance : O(n^2)
Best-case performance : O(n^2)
Average-case performance : O(n^2)
For more details click here

Code

/*****Selection Sort*****/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//Function defination
int* selection_sort(int *arr,int *n){
 int i,j,temp;
 for(i=0;i<*n-1;i++)
  for(j=i+1;j<*n;j++)
   if(arr[i]>arr[j]){
    //Swapping
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
   }
 return arr;
}
//Starting the main function
int main(){
 int *arr,n,i;
 while(1){
  //Taking the number of element
  printf("\nEnter the number of element you want to store:");
  scanf("%d",&n);
  if(n<=0){
   printf("\nAn array size must be a positive integer.");
   continue;
  }
  else
   break;
 }
 //Create array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr){
  printf("\nNot enough memory.");
  exit(0);
 }
 //Taking the element from user
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 //Print the array before sorting
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 //Call the sorting function
 arr=selection_sort(arr,&n);
 //Print the sorted array
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 return 0;
}

Output

Enter the number of element you want to store:7

Enter the element(s) in the array:
Element[1]:2

Element[2]:4

Element[3]:1

Element[4]:5

Element[5]:8

Element[6]:7

Element[7]:3

The element(s) before sorting: 2 4 1 5 8 7 3
The element(s) after sorting: 1 2 3 4 5 7 8