

Sort a binary array using one traversal in Java
source link: http://adnjavainterview.blogspot.com/2019/06/sort-binary-array-using-one-traversal.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Sort a binary array using one traversal in Java
In the current post, we can discuss the binary sort i.e 0 and 1 in Java. Given a binary array contains 0 & 1 in unsorted order, the output should be in sorted but we have to traverse only once.
Example:-
Input , array - {0,1,1,0,0,0,1,0,1}
Output, array - {0,0,0,0,0,1,1,1,1}
Java code:-
SortBinaryArray.java
package com.practice; public class SortBinaryArray { public static void main(String[] args) { int arr[] = {1, 0, 1, 0, 0, 1, 1}; SortBinaryArray sort = new SortBinaryArray(); sort.sortBinaryArray(arr); for (int i =0; i<arr.length; i++) { System.out.print(arr[i]+" "); } } private void sortBinaryArray(int arr[]) { int length = arr.length; int j = -1; for (int i = 0; i < length; i++) { if (arr[i] < 1) { j++; int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } }
Output:- 0 0 0 1 1 1 1
Related Posts:-
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to implement Selection Sort
3) Implementation of merge sort in Java
4) Java Object sorting example (Comparable and Comparable)
5) Difference between Comparable and Comparator Interface in Java
6) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
7) Java program to find second largest number in an array
Recommend
-
17
题目¶ 原题地址:https://leetcode.com/problems/binary-tr...
-
16
题目¶ 原题地址:https://leetcode.com/problems/binary-...
-
15
题目¶ 原题地址:https://leetcode.com/problems/binary-tree-...
-
20
题目¶ 原题地址:https://leetcode.com/proble...
-
20
题目¶ 原题地址:https://leetcode.com/problems/bin...
-
5
leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)_快乐de胖虎-CSDN博客题目: Binary Tree Level Order Traversal II(由于Binary Tree Level Order Traversal I 这个题目只是在II的基础上少了一步...
-
11
题目: Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1...
-
11
Delete an element from array (Using two traversals and one traversal)Skip to content
-
6
Modify a binary tree to get preorder traversal using right pointers onlyModify a binary tree to get preorder traversal using right pointers only02/06/2022
-
9
Write a program to compute the in-order traversal of a binary tree using O(1) space. Python
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK