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

Assignment

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Assignment

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Assignment:

Submitted by:
Muhammad Afrasiyab Khan
Khattak
Submitted to:
Sir Tahseen Haider
Date:
5 May 2024
Input Array: [4 6 3 2 1 9 7 ]
Selection Sorting:
Code:
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {4, 6, 3, 2, 1, 9, 7};
System.out.println("Input Array: " + Arrays.toString(arr));
selectionSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr, i, minIndex);
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Output:

Insertion Sorting:
Code:
import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {4, 6, 3, 2, 1, 9, 7};
System.out.println("Input Array: " + Arrays.toString(arr));
insertionSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
Output:

Bubble Sorting:
Code:
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {4, 6, 3, 2, 1, 9, 7};
System.out.println("Input Array: " + Arrays.toString(arr));
bubbleSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Output:

You might also like