Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Bubble Sort in Java

The document explains the bubble sort algorithm in Java, which is a simple sorting method that compares adjacent elements and swaps them if they are in the wrong order. It provides a sample Java program that demonstrates how to implement bubble sort on an array of integers. The output shows the array before and after sorting, illustrating the effectiveness of the algorithm.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Bubble Sort in Java

The document explains the bubble sort algorithm in Java, which is a simple sorting method that compares adjacent elements and swaps them if they are in the wrong order. It provides a sample Java program that demonstrates how to implement bubble sort on an array of integers. The output shows the array before and after sorting, illustrating the effectiveness of the algorithm.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

9/6/2018 Bubble Sort in Java - Javatpoint

Bubble Sort in Java


We can create a java program to sort array elements using bubble sort.
Bubble sort algorithm is known as the simplest sorting algorithm.

In bubble sort algorithm, array is traversed from first element to last


element. Here, current element is compared with the next element. If
current element is greater than the next element, it is swapped.

public class BubbleSortExample {


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();

https://www.javatpoint.com/bubble-sort-in-java 1/2
9/6/2018 Bubble Sort in Java - Javatpoint

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] + " ");
}

}
}

Output:

Array Before Bubble Sort


3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320

← prev next →

Please Share

Learn Latest Tutorials

DS PDFBox Ant


JMeter jBPM

https://www.javatpoint.com/bubble-sort-in-java 2/2

You might also like