see pic Given an n-element unsorted array A of n integers and an integer k, writ
ID: 3543173 • Letter: S
Question
see pic
Given an n-element unsorted array A of n integers and an integer k, write a recursive method for rearranging the elements in A so that all elements less than or equal to k come before any elements larger than k. What is the running time of your algorithm? Write a complete program that takes as input two lines: the first line contains two integers, call them n and k, where n 10. The next line contains the n integers of the array. The output of your program should be a single line containing the rearranged elements of A.Explanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
public class nsum {
static int n, r;
static ArrayList<Integer> array=new ArrayList<Integer>();
static ArrayList<Integer> arrayless=new ArrayList<Integer>();
static ArrayList<Integer> arraylarge=new ArrayList<Integer>();
static ArrayList<Integer> arraysame=new ArrayList<Integer>();
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("enter n r:");
String[] s=in.nextLine().split(" ");
n=Integer.parseInt(s[0]);
r=Integer.parseInt(s[1]);
System.out.println("enter the integers : ");
String[] values=in.nextLine().split(" ");
for(int i=0;i<n;i++){
array.add( Integer.parseInt(values[i]));
System.out.println( Integer.parseInt(values[i]));
array.get(i);
}
arrange(0);
for(int i=0;i<array.size();){array.remove(i);}
for(int i=0;i<arrayless.size();i++){array.add(arrayless.get(i));}
for(int i=0;i<arraysame.size();i++){array.add(arraysame.get(i));}
for(int i=0;i<arraylarge.size();i++){array.add(arraylarge.get(i));}
for(int i=0;i<array.size();i++){System.out.print(array.get(i)+" ");}
}
public static void arrange(int i){
System.out.println(i+" "+n);
if(i<n){
System.out.println(i+" "+n);
if(array.get(i)<r && i<n){ int temp=i+1;arrayless.add(array.get(i));arrange(temp);}
else if(array.get(i)>r&&i<n) {int temp=i+1;arraylarge.add(array.get(i));arrange(temp);}
else if(array.get(i)==r&&i<n) {int temp=i+1;arraysame.add(array.get(i));arrange(temp);}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.