Monday 15 June 2015

java - Creating a custom sort for an array of integers? -



java - Creating a custom sort for an array of integers? -

right, have 2 part sorting algorithm. it's based on array of 14 random integers. example:

int[] = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};

now, first thing i'm trying figure out how count how many number exists in original array. so, know 1 exists once, , 2 exists 4 times in original array. easy visually see this, if don't have access original array. need craft method count how many of each number 1-9 exists , set in new array called count. index 0 in count represent integer 1 , have value of 1. index 1 represent integer 2 , have value of 4. , on , forth. here i've got far i'm stuck. sorting pretty challenging me.

public static void main(string[] args) { // int[] countfinal = {1,4,1,2,1,0,1,2,2}; // number of times number 1-9 appears in a[]. // int[] sortedfinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // need final product. int[] = {9,2,4,8,9,4,3,2,8,1,2,7,2,5}; //int[] count = {}; int[] sorted = {}; counthowmany(a, 1); counthowmany(a, 2); counthowmany(a, 3); counthowmany(a, 4); counthowmany(a, 5); counthowmany(a, 6); counthowmany(a, 7); counthowmany(a, 8); counthowmany(a, 9); } public static int counthowmany(int[] array, int value) { // gathering count how many times number 1-9 exists , adding count[]; int howmanycount = 0; (int = 0; < array.length; i++) { if (array[i] == value) { howmanycount++; } } system.out.println(howmanycount); count = new int[9]; count[howmanycount]; system.out.println(arrays.tostring(count); // testing input homecoming howmanycount; }

it appears count number of times item in array exists properly. gotta figure out how can add together value new array count[] , each counthowmany(). part i'm stuck on.

once have figured out count[] can utilize create sorted[]. sorted supposed take info original array , count[] , create new array sorts in ascending order , allows duplicates. so, since 1 occurs 1 time , 2 occurs 4 times, new array sorted[] = {1, 2, 2, 2, 2, ...}

it's relatively little programme , little amount of integers, it's ok create array's necessary. key beingness i'm limited using arrays , cannot utilize arraylists this.

you don't need count each value individually. can iterate through entire array , increment counters each element encounter it.

int counts = new int[20]; // take value that's bigger in array. int[] = {9,2,4,8,9,4,3,2,8,1,2,7,2,5}; (int value : a) { counts[value]++; }

if don't know largest value in array be, you're improve utilize either map store counts, or kind of list increment size of needed.

java arrays algorithm sorting

No comments:

Post a Comment