0% found this document useful (0 votes)
18 views4 pages

Assignment No 4 DSA

Uploaded by

Soban Janjua
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)
18 views4 pages

Assignment No 4 DSA

Uploaded by

Soban Janjua
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/ 4

Data Structure And Algorithm

Assignment NO #04
Submitted By:
 Muhammad Soban Rasheed
Roll Number:
 FA20-BCS-020
Submitted To:
 Sir Javid Ali
Section:
 BCS ‘4A’
Date of Submission:
 27-06-2022

Selection Sorting:
public class selectionsorting {
public static void printArray(int arr[]) {
for (int i=0;i<arr.length;i++) {

System.out.print(arr[i] + " ");


}
System.out.println( );
}

public static void main(String[] args) {


int arr[]={7,8,3,1,2};

//selection sort
for (int i=0; i<arr.length-1 ;i++){
int smallest = i;
for (int j=i+1;j<arr.length;j++){
if (arr[smallest]>arr[j]){
smallest=j;

}
}
int temp=arr[smallest];
arr[smallest]=arr[i];
arr[i]=temp;

}
printArray(arr);
}

Insertion Sorting:
public class insertionsorting {
public static void printArray(int arr[]) {
for (int i=0;i<arr.length;i++) {

System.out.print(arr[i] + " ");


}
System.out.println( );
}

public static void main(String[] args) {


int arr[]={7,8,3,1,2};

for (int i=1;i<arr.length;i++){


int current=arr[i];
int j=i-1;

while (j>=0 && current < arr[j]){


arr[j+1]=arr[j];
j--;
}

arr[j+1]=current;

}
printArray(arr);
}
}
Merge Sorting:

public class mergingarray {


public static void conquer(int arr[], int si, int mid, int ei) {
int merged[] = new int[ei - si + 1];
int idx1 = si;
int idx2 = mid + 1;
int x = 0;
while (idx1 <= mid && idx2 <= ei) {
if (arr[idx1] <= arr[idx2]) {

merged[x++] = arr[idx1++];
} else {
merged[x++] = arr[idx2++];
}
}
while (idx1 <= mid) {
merged[x++] = arr[idx1++];
}
while (idx2 <= ei) {
merged[x++] = arr[idx2++];
}
for (int i = 0, j = si; i < merged.length; i++, j++) {
arr[j] = merged[i];
}
}

public static void divide(int arr[], int si, int ei) {


if (si >= ei) {
return;
}
int mid = si + (ei - si) / 2;
divide(arr, si, mid);
divide(arr, mid + 1, ei);
conquer(arr, si, mid, ei);
}

public static void main(String args[]) {


int arr[] = {6, 3, 9, 5, 2, 8};
int n = arr.length;
divide(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}

}
THE END..!

You might also like