> 12. Bubble Sort in Java (for integers)
Arrays in Java: (Part 8)
One Dimensional Array Bubble Sort:
12. Bubble Sort in Java (for integers)
13. Bubble Sort in Java (for Strings)
- Example: Bubble Sort in Java (for Integers)
- Example: Bubble Sort in Java (for Strings)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class bubble { | |
public static void main(String []args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.println("number of elements: "); | |
int n = scan.nextInt(); | |
int array[] = new int[n]; | |
System.out.println("Enter " + n + "elements"); | |
for (int i=0; i<n; i++){ | |
array[i] = scan.nextInt(); | |
} | |
for (int i=0; i<n-1;i++) { | |
for (int j=0; j<n-i-1;j++) { | |
if (array[j] > array[j+1]) /* for descending order use < */ | |
{ | |
int temp=array[j]; | |
array[j]=array[j+1]; | |
array[j+1]=temp; | |
} | |
} | |
} | |
System.out.println("\nsorted array: "); | |
for (int i=0; i<n;i++) { | |
System.out.println(array[i]); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class bubble { | |
public static void main(String []args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.println("number of elements: "); | |
int n = scan.nextInt(); | |
String array[] = new String[n]; | |
System.out.println("Enter " + n + "elements"); | |
for (int i=0; i<n; i++){ | |
array[i] = scan.next(); | |
} | |
for (int i=0; i<n-1;i++) { | |
for (int j=0; j<n-i-1;j++) { | |
if (array[j].compareToIgnoreCase(array[j+1]) > 0 )/* for descending order use < 0 */ | |
{ | |
String temp=array[j]; | |
array[j]=array[j+1]; | |
array[j+1]=temp; | |
} | |
} | |
} | |
System.out.println("\nsorted array: "); | |
for (int i=0; i<n;i++) { | |
System.out.println(array[i]); | |
} | |
} | |
} |
Comments
Post a Comment