0% found this document useful (0 votes)
10 views

21BCE8722 - Assignment2 1

The document discusses implementing merge sort and quick sort algorithms in Java. It includes code snippets showing how to write merge sort and quick sort methods as well as a main method to test sorting an integer array for each algorithm.

Uploaded by

aryxnshinde
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

21BCE8722 - Assignment2 1

The document discusses implementing merge sort and quick sort algorithms in Java. It includes code snippets showing how to write merge sort and quick sort methods as well as a main method to test sorting an integer array for each algorithm.

Uploaded by

aryxnshinde
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

CSE3004- DESIGN AND ANALYSIS OF ALGORITHM

Lab Assignment-2

Name - Aryan Anil Shinde


Registration Number - 21BCE8722

Merge Sort in Java:


import java.util.Arrays;

public class MergeSort {

public static void mergeSort(int[] arr) {


if (arr.length > 1) {
int mid = arr.length / 2;
int[] leftHalf = Arrays.copyOfRange(arr, 0, mid);
int[] rightHalf = Arrays.copyOfRange(arr, mid, arr.length);

mergeSort(leftHalf);
mergeSort(rightHalf);

merge(arr, leftHalf, rightHalf);


}
}

public static void merge(int[] arr, int[] left, int[] right) {


int i = 0, j = 0, k = 0;

while (i < left.length && j < right.length) {


if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}

while (i < left.length) {


arr[k] = left[i];
i++;
k++;
}

while (j < right.length) {


arr[k] = right[j];
j++;
k++;
}
}

public static void main(String[] args) {


int[] arr = {12, 11, 13, 5, 6, 7};
mergeSort(arr);

System.out.println("Sorted array: " + Arrays.toString(arr));


}
}

Quick Sort in Java:


import java.util.Arrays;

public class QuickSort {

public static void quickSort(int[] arr, int low, int high) {


if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}

public static int partition(int[] arr, int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

int temp = arr[i + 1];


arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}

public static void main(String[] args) {


int[] arr = {12, 11, 13, 5, 6, 7};
quickSort(arr, 0, arr.length - 1);

System.out.println("Sorted array: " + Arrays.toString(arr));


}
}

You might also like