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



2 comments:

  1. I recently explored techedc com, and it offers remarkable tutorials, detailed guides, and tech tips. The website’s organized layout and informative content make learning new technologies easy, enjoyable, and engaging for beginners and advanced users alike.

    ReplyDelete

  2. I highly appreciate NewsHyper for its dedication to delivering fact-checked and timely news. Every visit to the site offers valuable insights, ensuring readers remain informed and confident that the information from NewsHyper is both credible and relevant.

    ReplyDelete

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