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

Bubble Sort in C language

Bubble 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)
Average-case performance : O(n^2)
For more details click here

Code

/******Bubble Sort*****/

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

//Function defination
int* bubble_sort(int *arr,int *n){
 int i,j,flag,temp;
 for(i=*n-1;i>=0;i--) {
  flag=0;
  for(j=0;j<i;j++)
   if(arr[j]>arr[j+1]){
    //Swapping
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
    flag=1;
   }
  if(flag==0)
   break;
 }
 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;
 }
 //Creating array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr){
  printf("\nNot enough memory.");
  exit(0);
 }
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 arr=bubble_sort(arr,&n);
 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]:6

Element[2]:1

Element[3]:8

Element[4]:4

Element[5]:5

Element[6]:2

Element[7]:3

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