|
| 1 | +// QUESTION STATEMENT : |
| 2 | +/*Given an array nums with n objects colored red, white, or blue, |
| 3 | + sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. |
| 4 | +We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. |
| 5 | +You must solve this problem without using the library's sort function. |
| 6 | +
|
| 7 | + OR |
| 8 | +
|
| 9 | + https://leetcode.com/problems/sort-colors/ |
| 10 | + */ |
| 11 | + |
| 12 | +import java.util.Arrays; // imported the array class |
| 13 | + |
| 14 | +public class sort_colors { |
| 15 | + public static void main(String[] args) { // main function |
| 16 | + int []colors = {2,1,0,0,1,2,1}; // input |
| 17 | + sortColors(colors); // calling the method |
| 18 | + System.out.println(Arrays.toString(colors)); // printing the output |
| 19 | + } |
| 20 | + public static void sortColors(int[] arr) { // This question can be easily solved by implementing the bubble sort |
| 21 | + boolean swapped; // boolean to optimize it |
| 22 | + for(int i =0;i<arr.length;i++){ // first loop |
| 23 | + swapped = false; // till here boolean is false because nothing is swapped |
| 24 | + for(int j = 1;j<arr.length-i;j++){ // this loop will compare two numbers |
| 25 | + if(arr[j]<arr[j-1]){ // and if the first one id greater |
| 26 | + int temp = arr[j]; // it will swap it |
| 27 | + arr[j]=arr[j-1]; |
| 28 | + arr[j-1]=temp; |
| 29 | + swapped = true; // boolean will become true |
| 30 | + } |
| 31 | + } |
| 32 | + if(!swapped){ // if nothing will swap means array is sorted |
| 33 | + break; // so it will break the loop |
| 34 | + } |
| 35 | + } |
| 36 | + } // method is of type VOID so nothing to return |
| 37 | +} |
0 commit comments