Thursday, January 18, 2024

Sort an array of 0s, 1s and 2s | Dutch National Flag problem

Sort an array of 0s, 1s and 2s |

Dutch National Flag problem


👀👀👀👀👀


/*

* This program defines a sortArray() method that sorts

* an array of 0s, 1s, and 2s using

* the Dutch National Flag algorithm.

*/


public class Sort012 {


public static void swap(int[] arr,int i,int j) {

int temp;

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

public static void sortArray(int[] arr) {

int low =0;

int mid =0;

int high =arr.length-1;

while(mid<=high) {

switch (arr[mid]) {

case 0:

swap(arr,low,mid);

low++;

mid++;

break;

case 1:

mid++;

break;

case 2:

swap(arr,mid,high);

high--;

break;

default:

break;

}

}

}


public static void main(String... aa) {

int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};

sortArray(arr);

for(int i:arr) {

System.out.print(i+" ");

}

}

}


Output:

0 0 0 0 1 1 1 1 2 2 2 2



No comments:

Post a Comment

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts