Quicksort java arraylist implementation - java

I'm struggling with a really simple problem in java. I've implemented quicksort in java that works on arraylists and can take any value. The problem is that it works only for an arraylist lower than about 8000 size.
Can anyone tell me what's wrong with my program? I think it might be connected with recursion depth limit but i'm not sure (because sometimes it works for larger sizes and sometimes not). How can I improve my quicksort implementation so it will work for much larger size of Arraylist like 100000?
import java.util.ArrayList;
import java.util.Random;
public class QuickSort {
Random gener;
int temporary,genertype,NInts,flag;
ArrayList<Integer> mylist;
public QuickSort(int type,int ilosc){
gener = new Random();
mylist= new ArrayList<>();
this.genertype=type;
this.NInts=ilosc;
}
void generate(){
if(genertype==0){
for(int i=0;i<NInts;i++){
mylist.add(gener.nextInt(100000));
}
}else {
for(int i=0;i<NInts;i++){
mylist.add(NInts-i);
}
}
}
int count1(ArrayList<Integer> list,int counter1,int counter2){
while(list.get(0)<list.get(counter1)){
if(counter1==counter2){
flag=1;
return counter1;
}
counter1++;
}
flag=0;
return counter1;
}
int count2(ArrayList<Integer> list,int counter1,int counter2){
while(list.get(0)>list.get(counter2)){
if(counter1==counter2){
flag=1;
return counter2;
}
counter2--;
}
flag=0;
return counter2;
}
public ArrayList<Integer> sorting(ArrayList<Integer> list) {
ArrayList<Integer> left = new ArrayList<Integer>();
ArrayList<Integer> right = new ArrayList<Integer>();
int counter1,counter2;
if (list.size() == 1) {
return list;
}else {
counter1=1;
counter2=list.size()-1;
while(counter1!=counter2) {
counter1=count1(list,counter1,counter2);
if(flag==1)
break;
counter2=count2(list,counter1,counter2);
if(flag==1)
break;
temporary = list.get(counter1);
list.set(counter1, list.get(counter2));
list.set(counter2, temporary);
}
for (int i = 0; i < counter1; i++) {
left.add(list.get(i));
}
for (int i = counter1; i < list.size(); i++) {
right.add(list.get(i));
}
left = sorting(left);
right = sorting(right);
list=merge(left, right);
}
return list;
}
ArrayList<Integer> merge(ArrayList<Integer> left, ArrayList<Integer> right) {
if(left.get(0)>right.get(right.size()-1)){
right.addAll(left);
return right;
}
else{
left.addAll(right);
return left;
}
}
void printing(){
for(int k=0;k<NInts;k++){
System.out.print(" "+mylist.get(k));
}
}
public static void main(String[] args){
QuickSort instance = new QuickSort(1,1000);
instance.generate();
instance.mylist=instance.sorting(instance.mylist);
instance.printing();
}
}
Ps.If you see anything wrong in my code, let me know so I can improve it :)

There could be many reasons why your code could not run for large number of inputs. Mostly it could be because the Heap Size capacity specified for your application is overflown. This can be resolved by increasing Heap Size of your application (check out this stackoverflow link on how to increase the heap size of your application)

Related

This is a code for finding anagrams in string. How can I optimise further as its giving me TLE error

LeetCode Q:https://leetcode.com/problems/find-all-anagrams-in-a-string/
I believe what I have done is perfectly fine. However, it's giving me a TLE error. What changes do I have to do in order to run this program?
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int[] fors=new int[26];
int[] forp=new int[26];
for(int i=0;i<p.length();i++){
forp[p.charAt(i)-'a']++;
}
int k=p.length();
int len=s.length();
int i=0;
int j=0;
ArrayList<Integer> list=new ArrayList<>();
if(s.length()<p.length()) return list;
while(j<len){
fors[s.charAt(j)-'a']++;
if(j-i+1<k)j++;
if(j-i+1==k){
if(areSame(fors,forp)){
list.add(j-k+1);
fors[s.charAt(i)-'a']--;
i++;
j++;
}
}
}
return list;
}
public boolean areSame(int[] countS, int[] countP){
for(int i=0;i<26;i++){
if(countS[i]!=countP[i]){
return false;
}
}
return true;
}
}
I see 2 issues with your code. First, regarding TLE, you have an infinite loop because you iterate j and i only if the windows are equal.
if(areSame(fors,forp)){
list.add(j-k+1);
fors[s.charAt(i)-'a']--;
i++;
j++;
}
You should iterate i regardless. Fixing this is as simple as moving the iteration out of the if case.
if(areSame(fors,forp)){
list.add(j- p.length() +1);
}
fors[s.charAt(i)-'a']--;
i++;
Notice that I also move out the S - counter so that you keep moving even if the areSame checker is false.
The second issue is how you iterate j. By incrementing j before the areSame check, you check the windows 1 size too early. You can fix this by moving the j iteration to the end :)
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int[] fors=new int[26];
int[] forp=new int[26];
for(int i=0;i<p.length();i++){
forp[p.charAt(i)-'a']++;
}
int i=0;
int j=0;
ArrayList<Integer> list=new ArrayList<>();
if(s.length()<p.length()) return list;
while(j<s.length()){
fors[s.charAt(j)-'a']++;
if(j-i+1== p.length()){
if(areSame(fors,forp)){
list.add(j- p.length() +1);
}
fors[s.charAt(i)-'a']--;
i++;
}
j++;
}
return list;
}
public boolean areSame(int[] countS, int[] countP){
for(int i=0;i<26;i++){
if(countS[i]!=countP[i]){
return false;
}
}
return true;
}
}

Getting an error while implementing memoization in the java code

Memoization is giving me wrong answers. Please can some one help me out here. Without memorization, I am getting the right answers as in function targetBestR, but in the memoized function targetBestM, I am getting the wrong values being stored in the array list for the respective keys.
import java.util.ArrayList;
import java.util.HashMap;
public class TargetSumBest {
public static ArrayList<Integer> targetBestR(int n, int arr[]){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestR(rem, arr);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
return shortestCombo;
}
public static ArrayList<Integer> targetBestM(int n, int arr[], HashMap<Integer, ArrayList<Integer>> memo){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
if(memo.containsKey(n)) return memo.get(n);
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestM(rem, arr,memo);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
memo.put(n, shortestCombo);
return shortestCombo;
}
public static void main(String[] args) {
int n=8; int arr[]= {1,4,2};
System.out.println(targetBestM(n, arr, new HashMap<Integer, ArrayList<Integer>>()));
System.out.println(targetBestR(n, arr));
}
}//error
Was able to find the problem. The array passed into the HashMap keeps getting used and added to. Was able to fix it by creating new ArrayLists when reading and writing from the HashMap.
when reading...
if (memo.containsKey(n)) {
System.out.println(indent + n + " memo.get(n) = " + memo.get(n));
return new ArrayList<>(memo.get(n));
}
when writing...
memo.put(n, new ArrayList<>(shortestCombo));

Hackerrank Mark and Toys Question my solution not working for large input testcases

Below is the problem statement from hackerrank
Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if prices = [1,2,3,4] and Mark has k=7 to spend, he can buy items [1,2,3] for 6, or [3,4] for 7 units of currency. He would choose the first group of 3 items.
Below is code I wrote for this problem which involves backtracking technique
import java.util.ArrayList;
import java.util.Collections;
public class MarkAndToys {
static ArrayList<Integer> possibleSolutions = new ArrayList<>();
static boolean findSolution(int[] prices,int amount,int left,int length,int items){
// Base case: if whole array was iterated and amount is >=0 then we got a solution
if(left >= length){
if(amount>=0){
possibleSolutions.add(items);
return true;
}
return false;
}
// Key idea: prices[left] is chosen or it is not.
// Deal with prices[left], letting recursion
// deal with all the rest of the array.
// Recursive call trying the case that prices[left] is chosen --
// subtract it from amount in the call.
if (findSolution(prices,amount-prices[left],left+1,length,items+1)) return true;
// Recursive call trying the case that prices[left] is not chosen.
if (findSolution(prices,amount,left+1,length,items)) return true;
// If neither of the above worked, it's not possible.
return false;
}
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
if(findSolution(prices,k,0,prices.length,0)){
//if solutions are found then return maximum of them
return Collections.max(possibleSolutions);
}
return 0;
}
public static void main(String[] args) {
System.out.println(maximumToys(new int[]{1,12,5,111,200,1000,10}, 50));
}
}
This seems to be working fine:
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
Arrays.sort(prices);
int sum = 0;
int index = 0;
for(int i = 0; i < prices.length; i++) {
sum+=prices[i];
index = i;
if(sum > k) {
break;
}
}
return index;
}
package Scanarios;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Toys {
public static void main(String[] args) {
Toys t=new Toys();
int[] a = {3,6,2,1,4,5};
int q=1;
int n=6;
ArrayList<Integer> queries[]=new ArrayList[n];
ArrayList<Integer> result=new ArrayList();
for (int i = 0; i < n; i++) {
queries[i] = new ArrayList<Integer>();
}
queries[0].add(10);
queries[0].add(2);
queries[0].add(2);
queries[0].add(5);
result=t.maximumToys(n,a,q,queries);
System.out.println(result);
}
public ArrayList<Integer> maximumToys(int n, int a[], int q, ArrayList<Integer> queries[]) {
ArrayList<Integer> arrlist=new ArrayList();
for(int z=0;z<q;z++) {
int[] arr=queries[z].stream().mapToInt(i -> i).toArray();
int cost=arr[0];
int k=arr[1];
int count=0;
int[] proxyarr=new int[n-1];
proxyarr =removeBrokenPrice(a,arr,k);
Arrays.sort(proxyarr);
for(int i=0;i< proxyarr.length;i++) {
cost -=proxyarr[i];
if(cost > 0) {
count++; }else {
break;
}
}
arrlist.add(count);
}
return arrlist;
}
int[] removeBrokenPrice (int a[],int b[],int k){
int count=0;
for(int i=k;i <= b.length-1;i++) {
for(int j=0;j<a.length;j++) {
if(j==b[i]-1) {
a[j]=-1;
count++;
}
}
}
int[] proxyarr=new int[a.length-count];
for(int i=0,j=0;i< a.length;i++)
{
if(a[i]==-1) {
continue;
}else {
proxyarr[j++]=a[i];
}
}
return proxyarr;
}
}

time limit exceeded in a nested for-while loop

Could someone help me understand where this time limited exceeding comes from? The context is that in this threeSum method, given an array, I'm trying to record all possible combinations of three numbers that add up to 0. The original question comes from : https://leetcode.com/problems/3sum/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> retList = new ArrayList<List<Integer>>();
Arrays.sort(nums); // O(nlogn)
for (int i=0; i<nums.length-1; i++){
int pleft;
int pright;
if (i!=0){
pleft = i-1;
while((nums[pleft]==nums[i]) && (pleft-1 >=0)){
pleft--;
}
} else {
pleft = i;
}
if (i!=nums.length-2){
pright = i+1;
while((nums[pright]==nums[i]) && (pright+1 < nums.length-1)){
pright++;
}
} else {
pright = i;
}
int sum;
while (true){
sum = nums[pleft]+nums[pright]+nums[i];
if (sum==0){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[pleft]);
temp.add(nums[pright]);
temp.add(nums[i]);
retList.add(temp);
if (pleft-1>=0) pleft--;
if (pright+1<nums.length-1) pright++;
} else if (sum>0){
if (pleft-1>=0) pleft--;
} else { // less than zero
if (pright+1<nums.length-1) pright++;
}
}
}
return retList;
}
}
You're not breaking out of your while(true) loop. That code will just run forever and you won't return a value. You need to add a break or change the while (true) to while (condition)

QuickSort Algorithm naive implementation..but why doesn't it work?

I am very new to programming and java so please don't laugh at this :). now..i looked over the net for the right implementation of the QuickSort algorithm and i am aware of that. but i tried to implement it myself in the very innocent,basic way i could think of. actually creating two seperate arrays(left,right) and continue to sort them and so on...
this is the code:
package excercise;
public class MyQuickSort {
public static int list[] = {6,5,3,1,8,7,2,4};
public static int[] addNumberToArray(int array[],int num){
int newArray[] = new int[array.length+1];
for(int i = 0;i<array.length;i++){
newArray[i] = array[i];
}
newArray[newArray.length-1] = num;
array = newArray;
return array;
}
public static int[] partition(int arr[]){
while(arr.length>1){
int pivotIndex = (int)(arr.length/2);
int left[] = new int[0];
int right[] = new int[0];
for(int i = 0;i<arr.length;i++){
if(i==pivotIndex){
continue;
}
else if(arr[i]<=arr[pivotIndex]){
left = addNumberToArray(left,arr[i]);
}
else{
right = addNumberToArray(right,arr[i]);
}
}
int origPivot = arr[pivotIndex];
int k = 0;
while(k<left.length){
arr[k] = left[k];
k++;
}
arr[k] = origPivot;
k++;
while(k<arr.length){
arr[k] = right[k-(left.length+1)];
}
if(left.length>1){
partition(left);
}
if(right.length>1){
partition(right);
}
}
return arr;
}
public static void main(String[]args){
list = partition(list);
for(int i = 0;i<list.length;i++){
System.out.print(list[i]+" ");
}
}
}
but why this is getting stick in a loop and don't work? i don't understand what is wrong with this code..except that this is not very efficient (to say the least)! but i am stubborn and want to try and make it work anyway..if you have any advices it will be great! thx in advance
ok,this is the new code,after debugging everything seems to work fine,but when i want to print the new sorted arr,it still prints me the original unsorted array. the recursion turn the whole thing back to where it starts. how can i make it "save the steps"? where should i put a "return" call and what should i return?
public class MyQuickSort {
public static int list[] = {6,5,3,1,8,7,2,4};
public static boolean sorted;
public static int[] addNumberToArray(int arr[],int num){
int newArr[] = new int[arr.length+1];
for(int i = 0;i<arr.length;i++){
newArr[i] = arr[i];
}
newArr[newArr.length-1] = num;
arr = newArr;
return arr;
}
public static void partition(int arr[]){
while(!sorted){
int pivotIndex = (int)(arr.length/2);
int left[] = new int[0];
int right[] = new int[0];
for(int i = 0;i<arr.length;i++){
if(i==pivotIndex){
continue;
}
else if(arr[i]<=arr[pivotIndex]){
left = addNumberToArray(left,arr[i]);
}
else{
right = addNumberToArray(right,arr[i]);
}
}
int origPivot = arr[pivotIndex];
int k = 0;
while(k<left.length){
arr[k] = left[k];
k++;
}
arr[k] = origPivot;
k++;
while(k<arr.length){
arr[k] = right[arr.length-arr.length-(left.length+1)+k];
k++;
}
if(left.length>1){
partition(left);
}
if(right.length>1){
partition(right);
}
if(left.length<=1&&right.length<=1){
sorted = true;
}
}
}
public static void main(String[] args) {
partition(list);
for(int i = 0;i<list.length;i++){
System.out.print(list[i]+" ");
}
}
}
your algorithm gets stuck in this loop
while(k<arr.length){
arr[k] = right[k-(left.length+1)];
}
the reason is that you don't increment your k.
try
while(k<arr.length){
arr[k] = right[k-(left.length+1)];
k++;
}
Cool! your implementation seem logically depicting quicksort. However, please note that quicksort is not to be implemented using additional buffers. It should be sorted in its own main array, recursing the call passing just the start and end bounds. Your implementation is more of a mergesort style, using quicksort logic. And yes, you missed the k++ as stated by the commenter above.

Categories