Docsity

computer programming, Lecture notes of Programming Languages

Toggle sidebar
bg1
Search and Sort Algorithms
Common Sorting Algorithms
Sorting arranges data in a specific order, typically ascending or descending.
Bubble Sort is a simple comparison-based algorithm where each pair of adjacent
elements is compared and swapped if they are in the wrong order. This process
"bubbles" the largest elements to the end of the list in each pass.
Java Implementation (Optimized)
This version includes a swapped flag to stop the algorithm early if the array becomes
sorted before all passes are complete, making it more efficient for nearly sorted data.
import java.util.Arrays;
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
// Outer loop for number of passes
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Inner loop for adjacent comparisons
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap adjacent elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no elements were swapped, the array is already sorted
if (!swapped) break;
}
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original Array: " + Arrays.toString(data));
bubbleSort(data);
System.out.println("Sorted Array: " + Arrays.toString(data));
}
}
pf3
pf4
pf5

Partial preview of the text

Download computer programming and more Lecture notes Programming Languages in PDF only on Docsity!

Common Sorting Algorithms

Sorting arranges data in a specific order, typically ascending or descending.

Bubble Sort is a simple comparison-based algorithm where each pair of adjacent

elements is compared and swapped if they are in the wrong order. This process

"bubbles" the largest elements to the end of the list in each pass.

Java Implementation (Optimized)

This version includes a swapped flag to stop the algorithm early if the array becomes

sorted before all passes are complete, making it more efficient for nearly sorted data.

import java.util.Arrays;

public class BubbleSort { public static void bubbleSort(int[] arr) { int n = arr.length; boolean swapped;

// Outer loop for number of passes for (int i = 0; i < n - 1; i++) { swapped = false;

// Inner loop for adjacent comparisons // Last i elements are already in place for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap adjacent elements int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } }

// If no elements were swapped, the array is already sorted if (!swapped) break; } }

public static void main(String[] args) { int[] data = {64, 34, 25, 12, 22, 11, 90}; System.out.println("Original Array: " + Arrays.toString(data));

bubbleSort(data);

System.out.println("Sorted Array: " + Arrays.toString(data)); }

Selection sort works by repeatedly finding the smallest element from the unsorted part

of an array and swapping it with the first element of that part. This process moves from

left to right, building a sorted section at the front.

Java Implementation

Here is a complete program implementing the selection sort algorithm:

public class SelectionSort { // Logic for selection sort public static void selectionSort(int[] arr) { int n = arr.length;

// Move the boundary of the unsorted subarray one by one for (int i = 0; i < n - 1; i++) { // Find the minimum element in the unsorted part int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } }

// Swap the found minimum element with the first element of unsorted part int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } }

// Helper method to print the array public static void printArray(int[] arr) { for (int num : arr) { System.out.print(num + " "); } System.out.println(); }

public static void main(String[] args) { int[] data = {64, 25, 12, 22, 11};

System.out.println("Original Array:"); printArray(data);

selectionSort(data);

System.out.println("Sorted Array:"); printArray(data); }

Merge Sort is a Divide and Conquer algorithm that recursively splits an array into

halves until each subarray has only one element, then merges those sorted halves back

together. It is highly efficient for large datasets due to its consistent time.

Java Implementation

Below is a standard recursive implementation of the Merge Sort algorithm.

import java.util.Arrays;

public class MergeSort {

// Main function to sort the array public void sort(int arr[], int left, int right) { if (left < right) { // Find the middle point int mid = left + (right - left) / 2;

// Recursively sort the first and second halves sort(arr, left, mid); sort(arr, mid + 1, right);

// Merge the sorted halves merge(arr, left, mid, right); } }

// Function to merge two halves back into the original array void merge(int arr[], int left, int mid, int right) { // Calculate sizes of two subarrays to be merged int n1 = mid - left + 1; int n2 = right - mid;

// Create temporary arrays int L[] = new int[n1]; int R[] = new int[n2];

// Copy data to temporary arrays for (int i = 0; i < n1; ++i) L[i] = arr[left + i]; for (int j = 0; j < n2; ++j) R[j] = arr[mid + 1 + j];

// Initial indexes of first and second subarrays int i = 0, j = 0;

// Initial index of merged subarray int k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else {

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

// Copy remaining elements of L[] if any while (i < n1) { arr[k] = L[i]; i++; k++; }

// Copy remaining elements of R[] if any while (j < n2) { arr[k] = R[j]; j++; k++; } }

public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 7}; System.out.println("Original Array: " + Arrays.toString(arr));

MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length - 1);

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

Quick Sort is an efficient, divide-and-conquer sorting algorithm that partitions an array

into smaller sub-arrays based on a "pivot" element.

Java Implementation (Lomuto Partition)

The following implementation uses the last element of the array as the pivot.

import java.util.Arrays;

public class QuickSort { // Main method to test the sort public static void main(String[] args) { int[] data = {8, 7, 2, 1, 0, 9, 6}; System.out.println("Unsorted: " + Arrays.toString(data));

quickSort(data, 0, data.length - 1);

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