- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to implement bubble sort
Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large datasets as its average and worst case complexity is of Ο(n2) where n is the number of items.
Example
public class BubbleSort { 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]) { temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } public static void main(String[] args) { int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; 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); 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 2 5 -2 6 -3 8 0 -7 -9 4 Array After Bubble Sort -9 -7 -3 -2 0 2 4 5 6 8
Advertisements