Sorting means to sort elements in ascending or descending order .
In this program, the task is to take input of n no. of elements in , store it in array & then find whether the element entered by user is present in the array or not using linear search . Here , n is the no. of elements in array & Using for loop , we will get the values in order of a[0] , a[1] , - - - - till a[n] . Afterthat , we take 2 for loops for bubble sort 1 to execute bubble sort for all elements & another for swapping . In 2nd loop , we check if existing no. is greater than next no.(a[j+1]) then we swap these 2 no.s otherwise we continue till end of loop . In last when we come out of the loop we get a sorted array by bubble sort
#include<stdio.h>
#include<conio.h>
void bubblesort(int b[20],int);
void main()
{ int arr[20],n,i;
clrscr();
printf("\n\n program to sort array using bubble sort");
printf("\n enter no. of elements : ");
scanf("%d",&n);
printf("\n enter array now : \n");
for(i=0;i<n;i++)
{ printf(" enter a[%d] = ",i);
scanf("%d",&arr[i]);
}
printf("sorted list in ascending order = \n");
bubblesort(&arr,n);
for(i=0;i<n;i++)
{ printf("%d ",arr[i]);
}
getch();
}
void bubblesort(int b[20],int n)
{ int i,j,temp;
for(i=0;i<(n-1);i++)
{ for(j=0;j<(n-i-1);j++)
{ if(b[j]>b[j+1])
{ temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
}
In this program, the task is to take input of n no. of elements in , store it in array & then find whether the element entered by user is present in the array or not using linear search . Here , n is the no. of elements in array & Using for loop , we will get the values in order of a[0] , a[1] , - - - - till a[n] . Afterthat , we take 2 for loops for bubble sort 1 to execute bubble sort for all elements & another for swapping . In 2nd loop , we check if existing no. is greater than next no.(a[j+1]) then we swap these 2 no.s otherwise we continue till end of loop . In last when we come out of the loop we get a sorted array by bubble sort
#include<stdio.h>
#include<conio.h>
void bubblesort(int b[20],int);
void main()
{ int arr[20],n,i;
clrscr();
printf("\n\n program to sort array using bubble sort");
printf("\n enter no. of elements : ");
scanf("%d",&n);
printf("\n enter array now : \n");
for(i=0;i<n;i++)
{ printf(" enter a[%d] = ",i);
scanf("%d",&arr[i]);
}
printf("sorted list in ascending order = \n");
bubblesort(&arr,n);
for(i=0;i<n;i++)
{ printf("%d ",arr[i]);
}
getch();
}
void bubblesort(int b[20],int n)
{ int i,j,temp;
for(i=0;i<(n-1);i++)
{ for(j=0;j<(n-i-1);j++)
{ if(b[j]>b[j+1])
{ temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
}

No comments:
Post a Comment
Guys if you think something is wrong or should be edit than please do comment.