Worksheet - 2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Student Name: Khushal Jain UID: 20BCS3697

Branch: IS Section/Group: PH20BIS1-B


Semester: 4 Date of Performance: 21.03.22
Subject Name: DAA Lab MST

1. Aim/Overview of the practical:


WS Suppose you have been given a list of 100000 citizens of a country and you have been asked to sort the list
2 alphabetically. Which sorting algorithm you consider best to do this task and why. Also write program to
implement the sorting and find time complexity.

Merge sort will be the best algorithm for this task because it ensures the best time complexities
i.e. O(n log n).

Its overall time complexity is O(n log n).

Merge Sort is a stable sort which means that the same element in an array maintain their
original positions with respect to each other. It is efficient in the worst case as well.

2. Algorithm:

1. Mark the middle element from array as midpoint.


2. Divide the array into two parts from middle element.
3. Call the mergeSort function on left array.
4. Call the mergeSort function on right array.
5. Repeat step 3 and step 4 till array is sorted.
6. Join the two sorted arrays at the end of the program.
3. Code:
import java.util.*;
public class MergeSortLines {
    public static void main(String[] args) {
        String[] list = {"Khushal", "Jaswant", "Palak", "Aishworyann", "Raju"};
        System.out.println("before: " + Arrays.toString(list));
        mergeSort(list);
        System.out.println("after: " + Arrays.toString(list));
        System.out.println("\nNAME : Khushal Jain\t\tUID : 20BCS3697\n");
    }
    public static void mergeSort(String[] a) {
        if (a.length >= 2) {
            String[] left = new String[a.length / 2];
            String[] right = new String[a.length-a.length / 2];
            for (int i = 0; i < left.length; i++)
            {
                left[i] = a[i];
            }
            for (int i = 0; i < right.length; i++)
            {
                right[i] = a[i + a.length / 2];
            }
            mergeSort(left);
            mergeSort(right);
            merge(a, left, right);
        }
    }
    public static void merge(String[] result, String[] left, String[] right) {
        int i1 = 0;
        int i2 = 0;
        for (int i = 0; i < result.length; i++) {
        if (i2 >= right.length || (i1 < left.length &&
                             left[i1].compareToIgnoreCase(right[i2])<0)) {
                      result[i] = left[i1];
                      i1++;
                 } else {
                      result[i] = right[i2];
                      i2++;
                 }
            }
    }
}

Output:

Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):

Sr. No. Parameters Marks Obtained Maximum Marks


1.
2.
3.

You might also like