-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort01.java
60 lines (54 loc) · 1.29 KB
/
Sort01.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*Sort 0 1
You have been given an integer array/list(ARR) of size N that contains only integers, 0 and 1. Write a function to sort this array/list. Think of a solution which scans the array/list only once and don't require use of an extra array/list.*/
package Array_1D;
import java.util.Scanner;
public class Sort01
{
public static void sort(int arr[])
{
int zero = 0;
for(int i =0;i<arr.length;i++)
{
if(arr[i]==0)
{
zero++;
}
}
for(int i =0;i<arr.length;i++)
{
if(i<zero)
{
arr[i] = 0;
}
else
{
arr[i] = 1;
}
}
System.out.print("Sorted array ");
printArray(arr);
}
public static void printArray(int arr[])
{
for(int i= 0; i<arr.length; i++)
{
System.out.print(arr[i]+ ", ");
}
System.out.println();
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array : ");
int size = sc.nextInt();
int[] input = new int[size];
for(int i= 0; i<size; i++)
{
System.out.print("Enter the element at "+ i + "th term : ");
input[i] = sc.nextInt();
}
System.out.print("Original array ");
printArray(input);
sort(input);
}
}