This C Program sorts the numbers in ascending order using bubble sort. Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. Here we need to sort a number in ascending order.
Here is source code of the C program to sort the numbers in ascending order using bubble sort. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C program to sort N numbers in ascending order using Bubble sort
-
* and print both the given and the sorted array
-
*/
-
#include <stdio.h>
-
#define MAXSIZE 10
-
-
void main()
-
{
-
int array[MAXSIZE];
-
int i, j, num, temp;
-
-
printf("Enter the value of num \n");
-
scanf("%d", &num);
-
printf("Enter the elements one by one \n");
-
for (i = 0; i < num; i++)
-
{
-
scanf("%d", &array[i]);
-
}
-
printf("Input array is \n");
-
for (i = 0; i < num; i++)
-
{
-
printf("%d\n", array[i]);
-
}
-
/* Bubble sorting begins */
-
for (i = 0; i < num; i++)
-
{
-
for (j = 0; j < (num - i - 1); j++)
-
{
-
if (array[j] > array[j + 1])
-
{
-
temp = array[j];
-
array[j] = array[j + 1];
-
array[j + 1] = temp;
-
}
-
}
-
}
-
printf("Sorted array is...\n");
-
for (i = 0; i < num; i++)
-
{
-
printf("%d\n", array[i]);
-
}
-
}
$ cc pgm21.c $ a.out Enter the value of num 6 Enter the elements one by one 23 45 67 89 12 34 Input array is 23 45 67 89 12 34 Sorted array is... 12 23 34 45 67 89
This is a C Program to sort an array in ascending order.
Problem DescriptionThis program will implement a one-dimentional array of some fixed size, filled with some random numbers, then will sort all the filled elements of the array.
Problem Solution1. Create an array of fixed size (maximum capacity), lets say 10.
2. Take n, a variable which stores the number of elements of the array, less than maximum capacity of array.
3. Iterate via for loop to take array elements as input, and print them.
4. The array elements are in unsorted fashion, to sort them, make a nested loop.
5. In the nested loop, the each element will be compared to all the elements below it.
6. In case the element is greater than the element present below it, then they are interchanged
7. After executing the nested loop, we will obtain an array in ascending order arranged elements.
Program/Source CodeHere is source code of the C program to sort the array in an ascending order. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
-
/*
-
* C program to accept N numbers and arrange them in an ascending order
-
*/
-
-
#include <stdio.h>
-
void main()
-
{
-
-
int i, j, a, n, number[30];
-
printf("Enter the value of N \n");
-
scanf("%d", &n);
-
-
printf("Enter the numbers \n");
-
for (i = 0; i < n; ++i)
-
scanf("%d", &number[i]);
-
-
for (i = 0; i < n; ++i)
-
{
-
-
for (j = i + 1; j < n; ++j)
-
{
-
-
if (number[i] > number[j])
-
{
-
-
a = number[i];
-
number[i] = number[j];
-
number[j] = a;
-
-
}
-
-
}
-
-
}
-
-
printf("The numbers arranged in ascending order are given below \n");
-
for (i = 0; i < n; ++i)
-
printf("%d\n", number[i]);
-
-
}
Program Explanation
1. Declare an array of some fixed capacity, lets say 30.
2. From users, take a number N as input, which will indicate the number of elements in the array (N <= maximum capacity)
3. Iterating through for loops (from [0 to N) ), take integers as input from user and print them. These input are the elements of the array.
4. Now, create a nested for loop with i and j as iterators.
5. Start the sorting in ascending order by extracting each element at position i of outer loop.
6. This element is being compared to every element from position i+1 to size-1 (means all elements present below this extracted element)
7. In case any of the extracted element is greater than the element below it, then these two interchange their position, else the loop continues.
8. After this nested loop gets executed, we get all the elements of the array sorted in ascending order.
Runtime Test Cases
Enter the value of N
6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780
This is a C Program to sort the names in an alphabetical order.
Problem Description
The program will accept some names from the user as input & then sorts them in an alphabetical order using string operation.
Problem Solution
1. Create a 2D character array to store names of some fixed size.
2. Take names as input from users using for loop.
3. Now, sort this array of names using Selection sort.
4. Make a nested for loop, where the upper loop extracts each name and inner loop compares this name by the rest of the names below it.
5. After executing both the loops, rearranging all the names, finally an array of alphabetically sorted array will be obtained.
Program/Source Code
Here is source code of the C program to sort the names in an alphabetical order. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
-
/*
-
* C program to read N names, store them in the form of an array
-
* and sort them in alphabetical order. Output the given names and
-
* the sorted names in two columns side by side.
-
*/
-
-
#include <stdio.h>
-
#include <string.h>
-
void main()
-
{
-
-
char name[10][8], tname[10][8], temp[8];
-
int i, j, n;
-
-
printf("Enter the value of n \n");
-
scanf("%d", &n);
-
printf("Enter %d names n \n", n);
-
-
for (i = 0; i < n; i++)
-
{
-
scanf("%s", name[i]);
-
strcpy(tname[i], name[i]);
-
}
-
-
for (i = 0; i < n - 1 ; i++)
-
{
-
for (j = i + 1; j < n; j++)
-
{
-
if (strcmp(name[i], name[j]) > 0)
-
{
-
strcpy(temp, name[i]);
-
strcpy(name[i], name[j]);
-
strcpy(name[j], temp);
-
}
-
}
-
}
-
-
printf("\n----------------------------------------\n");
-
printf("Input NamestSorted names\n");
-
printf("------------------------------------------\n");
-
-
for (i = 0; i < n; i++)
-
{
-
printf("%s\t\t%s\n", tname[i], name[i]);
-
}
-
-
printf("------------------------------------------\n");
-
-
}
Program Explanation
1. Create two 2D character array of some fixed capacity.
2. Take the size of the array as input from the user, and fill the array with names taking them as input.
3. Now to sort this array, first make a nested for loop with i and j as iterators respectively.
4. The outer will will run from 0 to size – 1 , extracting each name of position i, one by one.
5. The inner loop will run from i+1 to size-1, comparing the name extracted by outer loop to all the names below it.
6. At each comparison, if the name above is alphabetically greater than the name below, then these two names are interchanged.
7. After executing the nested loop code section, we will obtain an array of names in proper alphabetical order.
Runtime Test Cases
Enter the value of n
7
Enter 7 names
heap
stack
queue
object
class
program
project
----------------------------------------
Input Names Sorted names
------------------------------------------
heap class
stack heap
queue object
object program
class project
program queue
project stack
------------------------------------------
C Program to Implement Selection Sort Recursively
This C Program implements a Selection sort. Selection sort works by finding the smallest unsorted item in the list and swapping it with the item in the current position. It is used for sorting unsorted list of elements.
Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
-
/*
-
* C Program to Implement Selection Sort Recursively
-
*/
-
#include <stdio.h>
-
-
void selection(int [], int, int, int, int);
-
-
int main()
-
{
-
int list[30], size, temp, i, j;
-
-
printf("Enter the size of the list: ");
-
scanf("%d", &size);
-
printf("Enter the elements in list:\n");
-
for (i = 0; i < size; i++)
-
{
-
scanf("%d", &list[i]);
-
}
-
selection(list, 0, 0, size, 1);
-
printf("The sorted list in ascending order is\n");
-
for (i = 0; i < size; i++)
-
{
-
printf("%d ", list[i]);
-
}
-
-
return 0;
-
}
-
-
void selection(int list[], int i, int j, int size, int flag)
-
{
-
int temp;
-
-
if (i < size - 1)
-
{
-
if (flag)
-
{
-
j = i + 1;
-
}
-
if (j < size)
-
{
-
if (list[i] > list[j])
-
{
-
temp = list[i];
-
list[i] = list[j];
-
list[j] = temp;
-
}
-
selection(list, i, j + 1, size, 0);
-
}
-
selection(list, i + 1, 0, size, 1);
-
}
-
}
$ cc pgm18.c
$ a.out
Enter the size of the list: 5
Enter the elements in list:
23
45
64
12
34
The sorted list in ascending order is
12 23 34 45 64
C Program to Implement Selection Sort Method using Functions
This C Program implements selection sort method using functions. Selection sort is among the simplest of sorting techniques. It works as follows: first find the smallest in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Here is source code of the C program to implement selection sort method using functions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
-
* C program for SELECTION sort which uses following functions
-
* a) To find maximum of elements
-
* b) To swap two elements
-
*/
-
#include <stdio.h>
-
-
int findmax(int b[10], int k);
-
void exchang(int b[10], int k);
-
void main()
-
{
-
int array[10];
-
int i, j, n, temp;
-
-
printf("Enter the value of n \n");
-
scanf("%d", &n);
-
printf("Enter the elements one by one \n");
-
for (i = 0; i < n; i++)
-
{
-
scanf("%d", &array[i]);
-
}
-
printf("Input array elements \n");
-
for (i = 0; i < n ; i++)
-
{
-
printf("%d\n", array[i]);
-
}
-
/* Selection sorting begins */
-
exchang(array, n);
-
printf("Sorted array is...\n");
-
for (i = 0; i < n; i++)
-
{
-
printf("%d\n", array[i]);
-
}
-
}
-
/* function to find the maximum value */
-
int findmax(int b[10], int k)
-
{
-
int max = 0, j;
-
for (j = 1; j <= k; j++)
-
{
-
if (b[j] > b[max])
-
{
-
max = j;
-
}
-
}
-
return(max);
-
}
-
void exchang(int b[10], int k)
-
{
-
int temp, big, j;
-
for (j = k - 1; j >= 1; j--)
-
{
-
big = findmax(b, j);
-
temp = b[big];
-
b[big] = b[j];
-
b[j] = temp;
-
}
-
return;
-
}
$ cc pgm33.c
$ a.out
Enter the value of n
4
Enter the elements one by one
57
90
34
78
Input array elements
57
90
34
78
Sorted array is...
34
57
78
90
C Program to Input Few Numbers & Perform Merge Sort on them using Recursion
The following C program, using recursion, performs merge sort. A merge sort is a sorting algorithm with complexity of O(nlogn). It is used for sorting numbers, structure, files.
Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
-
* C Program to Input Few Numbers & Perform Merge Sort on them using Recursion
-
*/
-
-
#include <stdio.h>
-
-
void mergeSort(int [], int, int, int);
-
void partition(int [],int, int);
-
-
int main()
-
{
-
int list[50];
-
int i, size;
-
-
printf("Enter total number of elements:");
-
scanf("%d", &size);
-
printf("Enter the elements:\n");
-
for(i = 0; i < size; i++)
-
{
-
scanf("%d", &list[i]);
-
}
-
partition(list, 0, size - 1);
-
printf("After merge sort:\n");
-
for(i = 0;i < size; i++)
-
{
-
printf("%d ",list[i]);
-
}
-
-
return 0;
-
}
-
-
void partition(int list[],int low,int high)
-
{
-
int mid;
-
-
if(low < high)
-
{
-
mid = (low + high) / 2;
-
partition(list, low, mid);
-
partition(list, mid + 1, high);
-
mergeSort(list, low, mid, high);
-
}
-
}
-
-
void mergeSort(int list[],int low,int mid,int high)
-
{
-
int i, mi, k, lo, temp[50];
-
-
lo = low;
-
i = low;
-
mi = mid + 1;
-
while ((lo <= mid) && (mi <= high))
-
{
-
if (list[lo] <= list[mi])
-
{
-
temp[i] = list[lo];
-
lo++;
-
}
-
else
-
{
-
temp[i] = list[mi];
-
mi++;
-
}
-
i++;
-
}
-
if (lo > mid)
-
{
-
for (k = mi; k <= high; k++)
-
{
-
temp[i] = list[k];
-
i++;
-
}
-
}
-
else
-
{
-
for (k = lo; k <= mid; k++)
-
{
-
temp[i] = list[k];
-
i++;
-
}
-
}
-
-
for (k = low; k <= high; k++)
-
{
-
list[k] = temp[k];
-
}
-
}
$ cc pgm28.c
$ a.out
Enter total number of elements:5
Enter the elements:
12
36
22
76
54
After merge sort:
12 22 36 54 76
C Program to Perform Quick Sort on a set of Entries from a File using Recursion
The following C program, using recursion, performs quick sort. A quick sort is a sorting algorithm with complexity of O(nlogn). It is used for sorting numbers, structure, files.
Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
-
* C Program to Perform Quick Sort on a set of Entries from a File
-
* using Recursion
-
*/
-
#include <stdio.h>
-
-
void quicksort (int [], int, int);
-
-
int main()
-
{
-
int list[50];
-
int size, i;
-
-
printf("Enter the number of elements: ");
-
scanf("%d", &size);
-
printf("Enter the elements to be sorted:\n");
-
for (i = 0; i < size; i++)
-
{
-
scanf("%d", &list[i]);
-
}
-
quicksort(list, 0, size - 1);
-
printf("After applying quick sort\n");
-
for (i = 0; i < size; i++)
-
{
-
printf("%d ", list[i]);
-
}
-
printf("\n");
-
-
return 0;
-
}
-
void quicksort(int list[], int low, int high)
-
{
-
int pivot, i, j, temp;
-
if (low < high)
-
{
-
pivot = low;
-
i = low;
-
j = high;
-
while (i < j)
-
{
-
while (list[i] <= list[pivot] && i <= high)
-
{
-
i++;
-
}
-
while (list[j] > list[pivot] && j >= low)
-
{
-
j--;
-
}
-
if (i < j)
-
{
-
temp = list[i];
-
list[i] = list[j];
-
list[j] = temp;
-
}
-
}
-
temp = list[j];
-
list[j] = list[pivot];
-
list[pivot] = temp;
-
quicksort(list, low, j - 1);
-
quicksort(list, j + 1, high);
-
}
-
}
$ cc pgm29.c
$ a.out
Enter the number of elements: 6
Enter the elements to be sorted:
67
45
24
98
12
38
After applying quick sort
12 24 38 45 67 98
2. C Examples on Searching Algorithms
C Program to Read an Array and Search for an Element
This is a C Program to read an array and search for an element.
Problem DescriptionThis program will implement a one-dimentional array, take a number form users to search for in the array using Binary Search.
Problem Solution1. Create an array of some certain size and define its elements in sorted fashion.
2. Now take an input from the users which you want to search for.
3. Take two variables pointing to the first and last index of the array (namely low and high)
4. Run start a while and run it until low equals high.
5. Now, take a mid of low and high value, check whether value at mid equals the user input.
6. In case it matches the user input, it means we found the number, after which we must break out from the loop.
7. And if user input is greater than value at mid, then low is assigned the value of mid. Similarly if user input is smaller than value at mid, then high is assigned the value of mid.
8. In this way, the region of finding the user input becomes half.Program/Source CodeHere is source code of the C program to read an array and search for an element. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program accept an array of N elements and a key to search.
* If the search is successful, it displays "SUCCESSFUL SEARCH".
* Otherwise, a message "UNSUCCESSFUL SEARCH" is displayed.
*/
#include <stdio.h>
void main(){
int array[20]; int i, low, mid, high, key, size; printf("Enter the size of an array\n"); scanf("%d", &size); printf("Enter the array elements\n"); for (i = 0; i < size; i++){
scanf("%d", &array[i]); } printf("Enter the key\n"); scanf("%d", &key);/* search begins */
low = 0; high = (size - 1); while (low <= high){
mid = (low + high) / 2; if (key == array[mid]){
printf("SUCCESSFUL SEARCH\n"); return;}
if (key < array[mid]) high = mid - 1;else
low = mid + 1;}
printf("UNSUCCESSFUL SEARCH\n");}
Program Explanation1. Declare an array of capacity 20, taking size from users, define all the element of the array but in sorted fashion.
2. Now, take three variables, low pointing to the first index of array i.e 0, last index of array i.e size-1, and mid.
3. Run a loop till the low become equal to high.
4. Inside this loop, first calculate mid using (high + low) / 2 = mid.
5. Check if the value at mid matches the user input, if it does, that means we found the element and now we can return by breaking out from the loop.
6. If user input is greater than value at mid, then low is shifted to mid, similarly if user input is smaller than mid, then high id shifted to mid.
7. In this way, each time, we halved the region where we are finding the element.Runtime Test CasesEnter the size of an array 4 Enter the array elements 90 560 300 390 Enter the key 90 SUCCESSFUL SEARCH $ a.out Enter the size of an array 4 Enter the array elements 100 500 580 470 Enter the key 300 UNSUCCESSFUL SEARCH
C Program to accept Sorted Array and do Search using Binary Search
This is a C Program to implement Binary Search Algorithm.
Problem DescriptionWe have to create a C Program which uses Binary search algorithm to predict that the element is present or not in the array. The user has to input a sorted array because binary search works on sorted array.
Problem Solution1. We will be having an array of numbers, we just need to find out whether the element is present in the array or not.
2. It can be done using Linear Search but it takes up a lot of time, so we need a better searching algorithm that performs the same task but in less time in comparison to Linear Search.
3. In worst case Linear Search takes O(n) time, but Binary Search takes O(log n) time in worst case.Expected Input and Output1. Average Case: When the element to be searched is other than the middle element. For example:
If the input array is {1, 2, 3, 4, 5, 6} and the key to be searched for is 6 then the expected output will be "Search Successful".Average case time complexity: O(log n).
2. Best Case: If the element to be searched is the middle element of the array. For example:
If the input array is {1, 5, 9} and the key to be searched is 5, then the expected output will be "Search Successful".Best case time complexity: O(1).
3. Worst Case: If the element to be searched for is not present in the array.
If the input array is {1, 3, 6, 8, 9} and the key to be searched for is 4, then the expected output will be "Search Unsuccessful".Worst case time complexity: O(log n).
Program/Source CodeHere is source code of the C Program to find whether the element is present in the array or not using Binary Search Algorithm. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.
/*
* C program to accept N numbers sorted in ascending order
* and to search for a given number using Binary Search.
* Report success or failure.
*/
#include <stdio.h>
- void main()
- {
- int array[10];
- int i, j, num, temp, keynum;
- int low, mid, high;
- printf("Enter the value of num \n");
- scanf("%d", &num);
- printf("Enter the elements one by one \n");
- for (i = 0; i < num; i++)
- {
- scanf("%d", &array[i]);
- }
- printf("Input array elements \n");
- for (i = 0; i < num; i++)
- {
- printf("%d\n", array[i]);
- }
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Binary searching begins */
low = 1;
high = num;
do
{
mid = (low + high) / 2;
if (keynum < array[mid])
high = mid - 1;
else if (keynum > array[mid])
low = mid + 1;
} while (keynum != array[mid] && low <= high);
- if (keynum == array[mid])
- {
- printf("SEARCH SUCCESSFUL \n");
- }
- else
- {
- printf("SEARCH FAILED \n");
- }
}
Program Explanation1. A Binary Search is a quick and efficient method of finding a specific target value from a set of ordered items. A Binary search is also known as a half-interval search.
2. Here in this program, the element to be searched is denoted by keynum.
3. In order to apply Binary Search, we need to have a sorted array. In the above program, we have used Bubble Sort before applying Binary Search.
4. After sorting the elements in ascending order, we have applied a binary search by first comparing the keynum with the middle element of the array.
5. If the value of keynum is equal to the middle element of the array, we have simply printed “SEARCH SUCCESSFUL”.
6. If keynum is other than the middle element of the array, we divide the array into two parts one having all the elements less than the middle element and the other having all the elements greater than the middle element, and start locating for keynum in the desired part.
7. If keynum is greater than the middle element, the value of low (starting index of the array), will become mid+1 and if it is less than the middle element high (last index of the array), will become mid-1. “mid” is the middle index of the array.
8. When we are modifying the values of low and high, we are basically dividing the array into two halves, and then looking for keynum in respective half.
9. The Best case time complexity of Binary Search is O(1). The only condition for implementing Binary Search is that the array should be sorted.Runtime Test Cases1. Enter the value of num 6 Enter the elements one by one 1 2 3 4 5 6 Input array elements 1 2 3 4 5 6 Sorted array is... 1 2 3 4 5 6 Enter the element to be searched 6 SEARCH SUCCESSFUL 2. Enter the value of num 3 Enter the elements one by one 1 5 9 Input array elements 1 5 9 Sorted array is... 1 5 9 Enter the element to be searched 5 SEARCH SUCCESSFUL 3. Enter the value of num 5 Enter the elements one by one 1 3 6 8 9 Input array elements 1 3 6 8 9 Sorted array is... 1 3 6 8 9 Enter the element to be searched 4 SEARCH FAILED