How do you sort an arraylist using insertion? Here is my arraylist it is filled with random Integers:
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++)
{
oh.add(random.nextInt());
}
Try this can help you to solve problem, sorting Arraylist with insertion sort.
public static void main(String args[]) {
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++) {
oh.add(random.nextInt());
}
int[] elementlist = new int[oh.size()];
Iterator<Integer> iter = oh.iterator();
for (int j = 0; iter.hasNext(); j++) {
elementlist[j] = iter.next();
}
int[] list = insertionSort(elementlist);
for (Integer in : list) {
System.out.println(in);
}
}
public static int[] insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int next = list[i];
// find the insertion location while moving all larger element up
int j = i;
while (j > 0 && list[j - 1] > next) {
list[j] = list[j - 1];
j--;
}
// insert the element
list[j] = next;
}
return list;
}
For more info go in link
import java.util.ArrayList;
public class InsertionSort {
private static ArrayList<Integer> inputArray = new ArrayList<Integer>();
public static ArrayList<Integer> getInputArray() {
return inputArray;
}
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.inputArray = inputArray;
}
public void sortGivenArray(){
for(int i=1;i<inputArray.size();i++){
int key = inputArray.get(i);
for(int j= i-1;j>=0;j--){
if(key<inputArray.get(j)){
inputArray.set(j+1,inputArray.get(j));
if(j==0){
inputArray.set(0, key);
}
}else{
inputArray.set(j+1,key);
break;
}
}
}
}
}
import java.util.ArrayList;
import daa.InsertionSort;
public class MainPractise implements Cloneable {
public static void main(String[] args) {
ArrayList<Integer> unsortedArray = new ArrayList<Integer>();
unsortedArray.add(8);
unsortedArray.add(7);
unsortedArray.add(6);
unsortedArray.add(5);
unsortedArray.add(4);
unsortedArray.add(0);
unsortedArray.add(2);
InsertionSort is = new InsertionSort(unsortedArray);
System.out.println("---------Initial Unsorted Array---------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
is.sortGivenArray();
System.out.println("\n------------Sorted Array------------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
}
}
Related
I'm trying to sort an array in ascending order. For some reason it only performs the for loop once. Why doesn't it keep going until everything is sorted?
It's for an assignment so I am not allowed to use existing sort methods. I'm supposed to write the method myself.
public class Sudoku {
public static void main(String[] args) {
int[] a = { 1, 4, 3, 5, 2 };
System.out.println(Arrays.toString(sortArray(a)));
}
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
return sortedArray;
}
}
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
output:[1, 2, 3, 4, 5]
or
//making use of j
public static int[] sortArray(int[] nonSortedArray){
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i <= nonSortedArray.length; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
arr = new int[Item];
Arrays.sort(arr);
Built in function in java to sort array in asceding order.
You are trying to sort an array using a single loop. You would be needing two loops to ensure that the elements are in sorted order.
public static int[] sortArray(int[] nonSortedArray)
{
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i < nonSortedArray.length-1; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
This will sort an array in ascending order
int arr[]={33,3,4,5,1};
Arrays.sort(arr);
System.out.println(Arrays.toString (arr));
output will:-[1,3,4,5,33]
Sorting array in ascending order
private static int[] sort(int[] array) {
int[] new_array = new int[array.length];
int count=0;
for (int i=0; i<array.length; i++) {
for(int j=i+1; j<array.length+i;j++) {
if(array[i]>=array[j%array.length])
count++;
}
for(int loc=count; loc>0;loc--) {
if(new_array[loc]==0)
{
new_array[loc]=array[i];
break;
}
}
count=0;
}
return new_array;
}
Okay, so i need to find all the negative numbers of array and return them.I found the negative number, but how do i return them all? P.S yes i am a beginner.
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
System.out.println(findNumber(array));
}
public static int findNumber(int[] sum) {
int num = 0;
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < num) {
num = sum[i];
}
}
return num;
}
Java 8 based solution. You can use stream to filter out numbers greater than or equal to zero
public static int[] findNumber(int[] sum)
{
return Arrays.stream(sum).filter(i -> i < 0).toArray();
}
There are multiple ways of doing this, if you just want to output all of the negative numbers easily you could do this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
ArrayList<Integer> negativeNumbers = findNumber(sum);
for(Integer negNum : negativeNumbers) {
System.out.println(negNum);
}
}
public static ArrayList<Integer> findNumber(int[] sum) {
ArrayList<Integer> negativeNumbers = new ArrayList<>();
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < 0) {
negativeNumber.add(sum[i]);
}
}
return negativeNumbers;
}
As you told you are beginner, i'm giving code in using arrays only.
Whenever you come across a negative number, just add it to the array and increment it's index number and after checking all the numbers, return the array and print it.
public static void main(String[] args)
{
int [] array = {5,-1,6,3,-20,10,20,-5,2};
int[] neg = findNumber(array);
for(int i = 0 ; i<neg.length; i++)
{
System.out.println(neg[i]);
}
}
public static int[] findNumber(int[] a)
{
int j=0;
int[] n = new int[a.length];
for(int i = 0; i<a.length ; i++)
{
if(a[i] <0)
{
n[j] = a[i];
j++;
}
}
int[] neg = new int[j];
for( int k = 0 ; k < j ; k++)
{
neg[k] = n[k];
}
return neg;
}
I hope it helps.
You can modify your method to iterate through the array of numbers, and add every negative number you encounter, to a List.
public static List<Integers> findNegativeNumbers(int[] num) {
List<Integers> negativeNumbers = new ArrayList<>();
for (int i = 0; i < num.length; i++) {
if(num[i] < 0) {
negativeNumbers.add(num[i]);
}
}
return negativeNumbers;
}
You could then print out the list of negative numbers from this method itself, or return the list with return to be printed in main.
You code is returning the sum of elements, but I understood that you wanted every negative number.
So, I assumed you want something like this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
Integer [] result = findNumbers( array );
for( int i : result )
{
System.out.println( i );
}
}
public static Integer[] findNumbers(int[] v) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < v.length ; i++) {
if(v[i] < 0) {
list.add(v[i]);
}
}
return list.toArray( new Integer[0] );
}
Is it?
Best regards.
public static int[] findNum(int[] array)
{
int negativeIntCount = 0;
int[] negativeNumbers = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] < 0)
{
negativeIntCount++;
negativeNumbers[i] = array[i];
}
}
System.out.println("Total negative numbers in given arrays is " + negativeIntCount);
return negativeNumbers;
}
To display as an array in output :
System.out.println(Arrays.toString(findNum(array)));
To display output as space gaped integers :
for(int x : findNum(array))
{
System.out.print(" " + x)
}
I need to return value from method permutation
public void permute(int []a,int k ) {
if(k==a.length)
jTextArea1.append(Arrays.toString(a)+"\n");
else
for (int i = k; i< a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
so what I need how to convert that to this
public int[] permute(int []a,int k ) {
.....
}
for expmle I have this code main
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3};
//p.permute(a, 0);
System.out.println((p.permute(a, 0)));
}
works .
but I need to do thats
public int[] permute(int []a,int k ) {
return
}
and give the result all permutation of a
I found the solution and I share the solation
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
for (int j = 0; j < l.size()+1; j++) {
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
import java.util.ArrayList;
import java.util.Random;
public class Merge {
private static ArrayList<Integer> newArrayList;
public static ArrayList<Integer> generateArray(int n){
newArrayList = new ArrayList<Integer>(n);
Random rand = new Random();
for (int i = 0; i<n; i++){
newArrayList.add(rand.nextInt(n + 1));
}
return newArrayList;
}
public static ArrayList<Integer> mergeSort(ArrayList<Integer> x){
if (x.size()>1){
ArrayList<Integer> ArrayList1 = new ArrayList<Integer>(x.size()/2);
ArrayList<Integer> ArrayList2 = new ArrayList<Integer>(x.size()-(x.size()/2));
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
for (int i = (newArrayList.size()/2); i<((newArrayList.size()/2)+(newArrayList.size()-newArrayList.size()/2)); i++){
ArrayList2.set(i-(newArrayList.size()/2), newArrayList.get(i));
}
//ArrayList1 = mergeSort(ArrayList1);
//ArrayList2 = mergeSort(ArrayList2);
int j = 0;
int k = 0;
int a = 0;
while(ArrayList1.size() != j && ArrayList2.size() != k){
if (ArrayList1.get(j) < ArrayList2.get(k)){
x.set(a, ArrayList1.get(j));
a++;
j++;
} else {
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
while (ArrayList1.size()!=j){
x.set(a, ArrayList1.get(j));
a++;
j++;
}
while (ArrayList2.size()!=k){
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
return x;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> new1;
//ArrayList<Integer> new2;
//ArrayList<Integer> new3;
new1 = generateArray(10);
//new2 = generateArray(100);
//new3 = generateArray(1000);
System.out.println(new1);
mergeSort(new1);
System.out.println(new1);
}
}
I am attempting to implement a mergeSort method but I keep getting the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.set(ArrayList.java:337)
at Merge.mergeSort(Merge.java:23)
at Merge.main(Merge.java:73)
Any ideas?
You are attempting to set a position that doesn't exist yet in your ArrayList called ArrayList1. You've set the initial capacity to x.size() / 2, but there's nothing in it yet.
It looks like you are attempting to set each position, starting with position 0, so just add the elements instead. Replace
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
with
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.add(newArrayList.get(i));
}
And you'll need to make similar changes to the for loop after that, which populates ArrayList2.
i want to write a app to find all possible combinations of n numbers of a given set of numbers and return a hashset of them..
for example if a give set{1,5,7,9} and size of set 2 then i will take:
[1, 5] [1, 7] [1, 9] [5, 7] [5, 9]
i have the following code from this post but i can't modified it for a given size of set every time.
import java.util.ArrayList;
import java.util.Arrays;
class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers,ArrayList<Integer> partial) {
System.out.println("sum("+Arrays.toString(partial.toArray())+")=");
for(int i=0;i<numbers.size();i++)
{
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j=i+1; j<numbers.size();j++)
remaining.add(numbers.get(j));
ArrayList<Integer> partial_rec = new ArrayList<Integer>(partial);
partial_rec.add(n);
sum_up_recursive(remaining,partial_rec);
}
}
static void sum_up(ArrayList<Integer> numbers) {
sum_up_recursive(numbers,new ArrayList<Integer>());
}
public static void main(String args[]) {
Integer[] numbers = {1,5,7,9};
sum_up(new ArrayList<Integer>(Arrays.asList(numbers)));
}
}
thank you all...
Also i found this solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class Comb {
static HashSet combine(Integer[] arr, int k, int startId, int[] branch, int numElem,HashSet arrSet)
{
if (numElem == k)
{
//System.out.println("k: "+k+(Arrays.toString(branch)));
ArrayList<Integer> mySet = new ArrayList<Integer>();
for(int i=0;i<branch.length;i++)
{
mySet.add(branch[i]);
}
arrSet.add(mySet);
return arrSet;
}
for (int i = startId; i < arr.length; ++i)
{
branch[numElem++]=arr[i];
combine(arr, k, ++startId, branch, numElem, arrSet);
--numElem;
}
return arrSet;
}
public static void main(String args[])
{
int k = 3;
Integer[] input ={1,5,7,9}; "ABCD".toCharArray();
int[] branch = new int[k];//{0,0};//new char[k];
HashSet arrSet=new HashSet();
arrSet=combine(input, k, 0, branch, 0, arrSet);
}
}
I changed recursive method from niiraj874u's answer to return a value. So now it gives list of hash sets as you wanted.
static List<Set<Integer>> sum_up_recursive(List<Integer> numbers,
Set<Integer> partial , int sizeOfset) {
List<Set<Integer>> result = new ArrayList<Set<Integer>>();
if(partial.size() == sizeOfset)
result.add(partial);
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++)
remaining.add(numbers.get(j));
Set<Integer> partial_rec = new HashSet<Integer>(partial);
partial_rec.add(n);
result.addAll(sum_up_recursive(remaining, partial_rec, sizeOfset));
}
return result;
}
public static void main(String args[]) {
Integer[] numbers = { 1, 5, 7, 9 };
int size = 2;
List<Set<Integer>> allCombinations = sum_up_recursive(Arrays.asList(numbers), new HashSet<Integer>(), size);
for (Set<Integer> set : allCombinations) {
for (Integer num : set)
System.out.print(num + " ");
System.out.println();
}
}
package com.app.atb;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Challenge {
public static void main(String[] args) {
Set<Integer> myset = new HashSet<Integer>();
myset.add(1);
myset.add(5);
myset.add(7);
myset.add(9);
List<Set<Integer>> achieved = solveChallenge(myset);
System.out.println(achieved);
}
public static List<Set<Integer>> solveChallenge(Set<Integer> myset) {
int n = myset.size();
Integer[] myInts = new Integer[n];
Iterator<Integer> iterator = myset.iterator();
int index = 0;
while (iterator.hasNext()) {
myInts[index] = iterator.next();
++index;
}
List<Set<Integer>> myList = new ArrayList<Set<Integer>>();
Set<Integer> subSet;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (j != i) {
subSet = new HashSet<Integer>();
subSet.add(myInts[i]);
subSet.add(myInts[j]);
myList.add(subSet);
}
}
}
return myList;
}
}
We can add one more parameter sizeOfset in SumSet.sum_up_recursive(ArrayList<Integer>, ArrayList<Integer>, int) method like below. please run it tell me Does it give the output what you want ?
import java.util.ArrayList;
import java.util.Arrays;
public class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers,
ArrayList<Integer> partial , int sizeOfset) {
if(partial.size() == sizeOfset)
{
System.out.println("sum(" + Arrays.toString(partial.toArray()) + ")=");
}
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++)
remaining.add(numbers.get(j));
ArrayList<Integer> partial_rec = new ArrayList<Integer>(partial);
partial_rec.add(n);
sum_up_recursive(remaining, partial_rec, sizeOfset);
}
}
static void sum_up(ArrayList<Integer> numbers) {
sum_up_recursive(numbers, new ArrayList<Integer>(), 2);
}
public static void main(String args[]) {
Integer[] numbers = { 1, 5, 7, 9 };
sum_up(new ArrayList<Integer>(Arrays.asList(numbers)));
}
}