Sorting Algorithm Implementation In C Language And Javascript | letsbug.com

   Sorting is a technique to rearrange the elements in ascending or descending order, which can be numerical, lexicographical, or any user-defined order. 

    For example, consider a telephone directory which consists of four fields; phone number, name, address, pin code.

    So a  large data is maintained in the form of records. If we want to search a phone number and name is is alphabetically sorted, then we can search easily. It would be very difficult if records were unsorted.

Following are some of the sorting methods:

  1. Bubble sort
  2. Insertion sort
  3. Merge sort
  4. Quick Sort
  5. Selection Sort

Assuming that you know some of programming, lets implement some of this algorithm below.

  1. Bubble sort
    • In this sorting, method, the list is divided into two sub-lists sorted and unsorted. The smallest element is bubbled from unsorted sub-list. After moving the smallest element the imaginary wall moves one element ahead.
    • Bubble sort In C language.                                                                        
      #include<stdio.h>
      #include<conio.h>
      #define MAX 20
      void bubbleSort(int A[MAX], int n);
      void display(int A[MAX], int n);
      void main()
      {
          int A[MAX], n, i;
          printf("Enter the number of elements in the Array: ");
          scanf("%d", &n);
          printf(" \n Enter the elements: \n\n");
          for(int i = 0; i < n; i++)
          {
              printf(" Array[%d] = ", i);
              scanf("%d", & A[i]);
          }
          bubbleSort(A, n);
          display(A, n);
          getch();
      }
      /* Bubble sort function */
      void bubbleSort(int A[MAX], int n)
      {
          int i, j, temp;
          for(i = 0; i < n; i++)
          {
              for(j = 0; j < n- i -1; j++)
              {
                  if(A[j] > A[j + 1])
                  {
                      /* Swap */
                      temp = A[j];
                      A[j] = A[j + 1];
                      A[j + 1] = temp;
                  }
              }
          }
      }
      /* Display the sorted array*/
      void display(int A[MAX], int n)
      {
          for(int i = 0; i< n; i++)
          {
              printf("%d", A[i]);
          }
      }
    • Bubble sort in Javascript.                                                                           

          /** bubble sort algorithm */
          let arr = []
          for(let i = 0; i < 10; i++){
              arr.push(Math.ceil(Math.random(1,10) * 10))
          }
          console.log(`Unsorted array is ${arr}`)
          //buble sort function

          function bubbleSort(a, n){
              for(let i = 0; i < n; i++){
                  for(let j = 0; j < n - i - 1; j++){
                      if(a[j] > a[j + 1]){
                          let temp = a[j]
                          a[j] = a[j + 1]
                          a[j + 1] = temp
                      }
                  }
              }
          }
          bubbleSort(arr, arr.length)
          console.log(`Sorted array is ${arr}`)
    • Video 

  2. Insertion Sort
    • In Insertion sort the element is inserted at an appropriate place. Here the array is divided into two parts sorted and unsorted sub-array. In each pass, the first element of unsorted sub array is picked up and moved into the sorted sub array by inserting it in suitable position.
    • Insertion sort in C language                                                                      
      #include<stdio.h>
      #include<conio.h>
      #define MAX 20
      //* insertionsort function */
      void insertionSort(int A[MAX], int n)
      {
          int i, j, key;
          for(i = 0; i < n; i++)
          {
              key = A[i];
              for(j = i -1; (j >= 0) && (key < A[j]); j--)
                  A[j + 1] = A[j];
                  A[j + 1] = key;
          }
      }
      void main()
      {
          int A[MAX], i, n;
          printf("Enter number of elements to sort? \n");
          scanf("%d", &n);
          printf("\n Enter the element into an array: \n");
          for(i = 0; i < n; i++)
          {
              scanf("%d", &A[i]);
          }
          insertionSort(A, n);
          printf("\n elements after sorting : \n");
          for( i = 0; i < n; i++)
          {
              printf("%d \t", A[i]);
          }
          getch();
      }
    • Insertion sort in Javascript                                                                        
          /** insertion Sort Algorithm */
          let arr = []
          for(let i = 0; i < 10; i++){
              arr.push(Math.ceil(Math.random(1, 200) * 100))
          }
          console.log(`Unsorted array is:[${arr}]`)

          function insertionSort(a, n){
              for(let i = 0; i <= n - 1; i++){
                  key = i
                  while(key > 0 && a[key] < a[key - 1]){
                      let temp = a[key]
                      a[key] = a[key - 1]
                      a[key - 1] = temp
                      key--
                  }
              }
          }

          insertionSort(arr, arr.length)
          console.log(`sorted array is : [${arr}]`)
  3. Quick Sort
    • It is more more popular and fastest sorting method. 
    • It follows divide and conquer methods i.e. numbers are divided and again subdivided and division goes on until it is not possible to divide further the procedure is applied recursively to the two parts of the array, on either side of the pivot element. It is also called partition-exchange sort.            
    • Quick sort in C language.                                                                           
      #include<stdio.h>
      #include<conio.h>
      #define MAX  20
      void quickSort(int[MAX], int, int);
      void main()
      {
          int low, high, pivot, t, n, i, j, a[MAX];
          printf("\n Number of elements for sorting \n");
          scanf("%d", &n);
          printf("\n Enter elements for array: ");
          for(i = 0; i < n; i++)
          {
              scanf("%d", &a[i]);
          }
          low = 0;
          high = n - 1;
          quickSort(a, low, high);
          printf("\n After sorting the elements are: ");
          for(i = 0; i < n; i++)
              printf("%d\t", a[i]);
          getch();
      }
      void quickSort(int a[ ], int low, int high)
      {
          int pivot, t, i, j;
          if(low < high)
          {
              pivot=a[low];
              i=low+1;
              j=high;
              while(i < j)
              {
                  while(pivot >= a[i] && i <=high)
                  {
                      j++;
                      while(pivot < a[j] && j >= low)
                      {
                          j--;
                      }
                      if(i < j)
                      {
                          t=a[i];
                          a[i]=a[j];
                          a[j]=t;
                      }
                  }
              }
              a[low] =a[j];
              a[j] = pivot;
              quickSort(a, low, j -1);
              quickSort(a,j + 1, high);
          }
      }
    • Quick sort in Javascript                                                                              
          /** quick Sort algorithm */
          let arr = []
          for(let i = 0; i < 10; i++){
              arr.push(Math.ceil(Math.random(1, 10) * 10))
          }
          console.log(`Unsorted array is ${arr}`)

          function partition(a, startIndex, endIndex){
              let pivot = a[endIndex]
              let i = startIndex - 1
              for(let j = startIndex; j <=endIndex; j++){
                  if(a[j] < pivot){
                      i++
                      let temp = a[i]
                      a[i] = a[j]
                      a[j] = temp
                  }
              }
              let temp = a[i + 1]
              a[i + 1] = a[endIndex]
              a[endIndex] = temp
              return i + 1
          }
          //quick sort function
          function quickSort(a, startIndex, endIndex){
              if(startIndex < endIndex){
                  let partitionIndex = partition(a, startIndex, endIndex)
                  quickSort(a, startIndex, partitionIndex - 1)
                  quickSort(a, partitionIndex + 1, endIndex)
              }
          }
          quickSort(arr, 0, arr.length - 1)
          console.log(`sorted array is ${arr}`)


    • video


  4. Merge Sort
    • The basic concept of merge sort is divides the list into tow smaller sub lists of approximately equal size. Recursively repeat this procedure till only one element is left in the sub list. After this, various sub lists are merged to form sorted parent list . This process goes on recursively till the original sorted list arrived.
    • Merge sort in C language                                                                          
      #include<stdio.h>
      #include<conio.h>
      void disp();
      void mergeSort(int, int, int);
      void msortdiv(int, int);
      int a[50], n;
      void main()
      {
          int i;
          printf("\n Enter the number of elements: ");
          scanf("%d", &n);
          printf("\n Enter the elements of array: \n");
          for(i = 0; i < n; i++)
              scanf("%d", &a[i]);
          printf("\n Before sorting elements are: \n");
          for( i = 0; i < n; i++)
              printf("%d\t", a[i]);
          msortdiv(0, n-1);
          printf("\n After sorting elements are: \n");
          for(i = 0; i < n; i++)
              printf("%d\t", a[i]);
          getch();
      }

      // mergeSort function
      void mergeSort(int low, int mid, int high)
      {
          int t[50], i, j, k;
          i = low;
          j = mid+1;
          k= low;
          while ((i <=mid) && (j <= high))
          {
              if(a[i] >= a[j])
                  t[k++] = a[j++];
              else
                  t[k++] = a[i++];
          }
          while (i <= mid)
              t[k++] = a[i++];
          while (j <= high)
              t[k++] = a[j++];
          for(i = low; i <= high; i++)
              a[i]=t[i];
      }

      void msortdiv(int low, int high)
      {
          int mid;
          if(low != high)
          {
              mid=((low+high)/2);
              msortdiv(low, mid);
              msortdiv(mid+1, high);
              mergeSort(low, mid, high);
          }
      }
  5. Selection Sort
    • This sorting algorithm, iterates through the array and finds the smallest number in the array and waps it with the first element if it  is smaller then the first element . Next, it goes on the second element and so on until all elements are sorted.
    • Selection sort in C language                                                                    
      #include<stdio.h>
      #include<conio.h>
      int main()
      {
          int array[100], n, i, j, position, t;
          printf("Enter number of elements \n");
          scanf("%d", &n);
          printf("Enter %d integers \n", n);
          for(i = 0; i < n; i++)
          {
              scanf("%d", &array[i]);
          }
          for(i = 0; i < (n - 1); i++)
          {
              position = i;
              for(j = i + 1; j < n; j++)
              {
                  if(array[position] > array[j])
                      position = j;
              }
              if(position != i)
              {
                  t = array[i];
                  array[i] = array[position];
                  array[position] = t;
              }
          }
          printf("Sorted list in ascending order: \n");
          for(i = 0; i < n; i++)
          {
              printf("%d\n", array[i]);
          }
          getch();
          return 0;
      }
    • Selection sort in Javascript                                                                       
          /** Selection sort algorithm */
          let arr = []
          for(let i = 0; i < 10; i++){
              arr.push(Math.ceil(Math.random(1, 10) * 10))
          }
          console.log(`unsorted array is ${arr}`)

          function selectionSort(a, n){
              let min_index = 0
              for(let i = 0; i < n - 1; i++){
                  min_index = i
                  for(let j = i + 1; j < n; j++){
                      if(a[min_index] > a[j]){
                          min_index = j
                      }
                  }
                  if(min_index != i){
                      let temp = a[i]
                      a[i] = a[min_index]
                      a[min_index] = temp
                  }
              }
          }
          selectionSort(arr, arr.length)
          console.log(`sorted array is ${arr}`)


    • Video                                                                                       

*If you have any doubt about any above code not working please ask in the comments*

Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug