import java.util.*;
public class javabasics {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.print("Enter the elements of array: ");
for (int i = 0; i < n; i ) {
arr[i] = sc.nextInt();
}
int idx = 0;
int ans[] = new int[n];
for (int i = 0; i < n; i ) {
if (arr[i] >= 0) {
ans[idx] = arr[i];
idx ;
}
for (int j = 0; j < n; j ) {
if (arr[i] < 0) {
ans[idx] = arr[i];
idx ;
}
}
for (int k = 0; k < n; k ) {
System.out.print(ans[i] " ");
}
}
}
}
The Question is : Given an unsorted array arr[] of size N having both negative and positive integers, place all negative elements at the end of array without changing the order of positive elements and negative elements. Input :
N = 8
arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }
Output :
1 3 2 11 6 -1 -7 -5
the code is not stoping to take input from the code and if i want to add greater than the size of array it bounces what should i do ?
CodePudding user response:
I think you missed the closure of the first for() loop
. And also you had some indexing issues.
I checked and fixed the code. Please compare it with your current code and learn from it.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.print("Enter the elements of array: ");
for (int i = 0; i < n; i ) {
arr[i] = sc.nextInt();
}
int idx = 0;
int ans[] = new int[n];
for (int i = 0; i < n; i ) {
if (arr[i] >= 0) {
ans[idx] = arr[i];
idx ;
}
}
for (int i = 0; i < arr.length; i ) {
if (arr[i] < 0) {
ans[idx] = arr[i];
idx ;
}
}
for (int k = 0; k < n; k ) {
System.out.print(ans[k] " ");
}
}
}