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

DSA Program For Practical

DSA

Uploaded by

Talha shabbir
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)
13 views

DSA Program For Practical

DSA

Uploaded by

Talha shabbir
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/ 3

Selection Sort

class selection {
public static void main(String str[]) {
int Arr[] = { 5, 4, 2, 1, 3 };
for (int i = 0; i < Arr.length; i++) {
for (int j = i + 1; j < Arr.length; j++) {
if (Arr[i] > Arr[j]) {
int temp = Arr[i];
Arr[i] = Arr[j];
Arr[j] = temp;
}
}
System.out.print(Arr[i] + ",");
}
}
}

Linear Search
public class linear {
public static void main(String[] args) {
int Arr[] = { 5, 4, 2, 1, 3 };
int F = 10;
int loc = 0;
for (int i = 0; i < Arr.length; i++) {
if (F == Arr[i]) {
loc = i;
}

}
if (loc == 0) {
System.out.println("not found");
} else {
System.out.println("found at location =" + loc);
}

}
}
Bubble Sort
public class bubble {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1] > arr[j]) {
// swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}

}
}

public static void main(String[] args) {


int arr[] = { 3, 60, 35, 2, 45, 320, 5 };

System.out.println("Array Before Bubble Sort");


for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);// sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");


for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

}
}
Binary Search
public class binary {
public static void main(String[] args) {
int Arr[] = { 1, 2, 3, 4, 5, 10, 16 };
int F = 1; //finding item
int b = 0; // beginning
int e = Arr.length - 1; //ending

while (b <= e) {
int mid = (b + e) / 2;
if (Arr[mid] == F) {
System.out.println("item found at loc=" + mid);
return;
} else if (F > Arr[mid]) {
b = mid + 1;
} else {
e = mid - 1;
}
if (b > e) {
System.out.println("item is not found");
}
}

}
}

You might also like