Bubble sort is a simple sorting algorithm that compares adjacent elements of an array and swaps them if the element on the right is smaller than the one on the left.
Program:
package demo;
import java.util.Arrays;
public class Bubblesort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {30,20,10,60,40};
for(int j=1;j<arr.length;j++) {
for(int i=0;i<arr.length-j;i++) {
if(arr[i]>arr[j]) {
int temp=arr[i+1];
arr[i+1]=arr[i];
arr[i]=temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
output:
[30, 10, 20, 40, 60]
Jagged array:
Jagged Arrays are special types of Multidimensional arrays which have variable number of columns. It is an array of arrays where each element is an array and can be of a different size.
program:
package demo;
import java.util.Scanner;
public class Jaggedarray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the row");
int row=sc.nextInt();
int a[][]=new int[row][];
for(int i=0;i<a.length;i++)
{
a[i]=new int[sc.nextInt()];
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
a[i][j]=sc.nextInt();
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+" ");
}System.out.println();
}
}
}
output:
Enter the row
3
3
2
1
1
1
1
1
1
1
1 1 1
1 1
1