bubble sort code definition
bubble sort in java
Sorting is the process of arranging data in a specific order, such as alphabetical, numerical, or chronological. Sorting can be done on a variety of data types, including numbers, strings, and objects.
Bubble sort: A simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order.
Asending Order :👇
code:
public class MyClass {
public static void printa(int arr[]){
for (int i = 0 ; i<arr.length;i++){
for (int j = 0; j<arr.length-1-i; j++){
if(arr[j]> arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void main(String args[]) {
int arr [] = {122,32,21,3,4,5,32,21,9};
printa(arr);
for(int e = 0; e<arr.length ; e++){
System.out.println(arr[e]);
}
}
}
OutPut:
3
4
5
9
21
21
32
32
122
Descending Order Code: 👇
class HelloWorld {
public static void Basicsort(int arr[]) {
for(int i = 0; i<arr.length;i++){
for (int j = 0 ; j<arr.length-1-i; j++){
if(arr[j] < arr[j+1]){
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = {41,3,5,1,2,7};
System.out.println("array length " + arr.length);
Basicsort(arr);
for (int i = 0; i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
OutPut:
array length 6
41
7
5
3
2
1
Explore More These: 👇👇
No comments: