You are on page 1of 15

EC-228 DSA

   LAB REPORT # 10

                   
Submitted by:
 Mahnoor Inam 
Amina Khalid
Reg. No: 
18-CE-009 
18-CE-017
Sunmitted to:
Sir Tauqeer
Date:
26-05-2020
Department of Computer Engineering
HITEC University Taxila
                                          Experiment # 10
Implementation of Sorting Algorithms in C++ programming language
Objectives:
The objective of this lab is to understand the basic concept of different sorting techniques

 Selection Sort
 Bubble Sort
 Insertion Sort
 Merge Sort

Theory:
A Sorting Algorithm is used to rearrange a given array or list elements according to a
comparison operator on the elements. The comparison operator is used to decide the new order
of element in the respective data structure. For example: The below list of characters is sorted in
increasing order of their ASCII values. That is, the character with lesser ASCII value will be
placed first than the character with higher ASCII value.
 The importance of sorting lies in the fact that data searching can be optimized to a very high
level, if data is stored in a sorted manner. Sorting is also used to represent data in more readable
formats.
Following are some of the examples of sorting in real-life scenarios −

 Telephone directory stores the telephone numbers of people sorted by their names, so that
the names can be searched easily.
 Dictionary stores words in an alphabetical order so that searching of any word becomes
easy.

Selection Sort:
We want to sort n elements store in an array. It’s a simple sorting algorithm which start by
looking within the array, the smallest element, and then swap it with the one in the first position,
then find the element with the second smallest value and swap it with the element in the second
position in the array, and then continue until the (n-1)th element is processed. We will then
obtain a sorted array.

Lab task:
Write C++ codes for all the above given algorithms that we have read in this
lab.

Merge Sort
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
    j = 0; 
    k = l; 
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        }
        else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
void mergeSort(int arr[], int l, int r)
{
    if (l < r) {
        int m = l + (r - l) / 2;

        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}
void printArray(int A[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", A[i]);
    printf("\n");
}
int main()
{
    int arr[] = { 12, 11, 13, 5, 6, 7 };
    int arr_size = sizeof(arr) /
sizeof(arr[0]);

    printf("Given array is \n");


    printArray(arr, arr_size);

    mergeSort(arr, 0, arr_size - 1);

    printf("\nSorted array is \n");


    printArray(arr, arr_size);
    return 0;
}

Output:

Bubble sort:
#include <stdio.h>
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
void bubbleSort(int arr[], int n)
{
   int i, j;
   bool swapped;
   for (i = 0; i < n-1; i++)
   {
     swapped = false;
     for (j = 0; j < n-i-1; j++)
     {
        if (arr[j] > arr[j+1])
        {
           swap(&arr[j], &arr[j+1]);
           swapped = true;
        }
     }
     if (swapped == false)
        break;
   }
}
void printArray(int arr[], int size)
{
    int i;
    for (i=0; i < size; i++)
        printf("%d ", arr[i]);
    printf("n");
}
int main()
{
    int arr[] = {64, 34, 25, 12, 22, 11,
90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

Output:
Insertion sort:
#include <bits/stdc++.h>
using namespace std;
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++)
    {
        key = arr[i];
        j = i - 1;
        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

void printArray(int arr[], int n)


{cout<<"sorted array is:";
    int i;
    for (i = 0; i < n; i++)
        cout <<arr[i] << " ";
    cout << endl;
}
int main()
{
    int arr[] = { 12, 11, 13, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);

    insertionSort(arr, n);
    printArray(arr, n);

    return 0;
}
Output:

Selection sort:
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
void selectionSort(int arr[], int n)
{
    int i, j, min_idx;
    for (i = 0; i < n-1; i++)
    {
        min_idx = i;
        for (j = i+1; j < n; j++)
        if (arr[j] < arr[min_idx])
            min_idx = j;
        swap(&arr[min_idx], &arr[i]);
    }
}
void printArray(int arr[], int size)
{
    int i;
    for (i=0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main()
{
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);
    selectionSort(arr, n);
    cout << "Sorted array: \n";
    printArray(arr, n);
    return 0;
}

Output:

Write a C++ program to implement any of the above algorithm to sort a single
linked list.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
void sortedInsert(struct Node**, struct Node*);
void insertionSort(struct Node **head_ref)
{
    struct Node *sorted = NULL;
    struct Node *current = *head_ref;
    while (current != NULL)
    {
        struct Node *next = current->next;
        sortedInsert(&sorted, current);
        current = next;
    }
    *head_ref = sorted;
}
void sortedInsert(struct Node** head_ref, struct Node* new_node)
{
    struct Node* current;
    /* Special case for the head end */
    if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
    {
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
    else
    {
        current = *head_ref;
        while (current->next!=NULL &&
               current->next->data < new_node->data)
        {
            current = current->next;
        }
        new_node->next = current->next;
        current->next = new_node;
    }
}
void printList(struct Node *head)
{
    struct Node *temp = head;
    while(temp != NULL)
    {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
}
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}
int main()
{
    struct Node *a = NULL;
    push(&a, 5);
    push(&a, 20);
    push(&a, 4);
    push(&a, 3);
    push(&a, 30);
 printf("Linked List before sorting \n");
    printList(a);
 insertionSort(&a);
printf("\nLinked List after sorting \n");
    printList(a);
return 0;
}

Output:

Write a C++ program to implement any of the above algorithm to sort a


double linked list.
#include <bits/stdc++.h>
using namespace std;
struct Node {
    int data;
    struct Node* prev, *next;
};
struct Node* getNode(int data)
{
    struct Node* newNode =
          (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->prev = newNode->next = NULL;
    return newNode;
}
void sortedInsert(struct Node** head_ref, struct Node* newNode)
{
    struct Node* current;
    if (*head_ref == NULL)
        *head_ref = newNode;
    else if ((*head_ref)->data >= newNode->data) {
        newNode->next = *head_ref;
        newNode->next->prev = newNode;
        *head_ref = newNode;
    }

    else {
        current = *head_ref;
        while (current->next != NULL &&
               current->next->data < newNode->data)
            current = current->next;
newNode->next = current->next;
        if (current->next != NULL)
            newNode->next->prev = newNode;

        current->next = newNode;
        newNode->prev = current;
    }
}
void insertionSort(struct Node** head_ref)
{
    struct Node* sorted = NULL;
    struct Node* current = *head_ref;
    while (current != NULL) {
        struct Node* next = current->next;
      current->prev = current->next = NULL;
        sortedInsert(&sorted, current);
        current = next;
    }
    *head_ref = sorted;
}
void printList(struct Node* head)
{
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
         (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    new_node->prev = NULL;
    if ((*head_ref) != NULL)
        (*head_ref)->prev = new_node;
    (*head_ref) = new_node;
}
int main()
{
    struct Node* head = NULL;
    push(&head, 9);
    push(&head, 3);
    push(&head, 5);
    push(&head, 10);
    push(&head, 12);
    push(&head, 8);
   cout << "Doubly Linked List Before Sorting: ";
    printList(head);
insertionSort(&head);
   cout << "\nDoubly Linked List After Sortingn: ";
    printList(head);
 return 0;
}

Output:

Conclusion:
In this lab we learned how to sort the array by using bubble sort, merge sort, selection sort and
insertion sort algorithm. And how it is apply to the single link list and in doubly link list.

END

You might also like