I need to sort in ascending order as I add object to my generic class (I'm using strings).
I'm using selection sort, but it is not working.
I don't know if it is the correct way of doing this, so would appreciate the input.
OrderSet class
public class OrderSet<T extends Comparable> implements Set<T> {
private T[] items;
private int size;
public OrderSet()
{
items = (T[]) new Comparable[5];
}
#Override
public void add(T s)
{
if(size >= items.length)
{
items = grow(items);
}
for(int i = 0; i < items.length; i++)
{
if(items[i] == null)
{
items[i] = s;
size++;
break;
}
}
if(size > 1)
{
for (int i = 0; i < size-1; i++)
{
for(int j = 1; j < size; j++)
{
T tmp;
if (items[i].compareTo(items[j]) > 0)
{
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
}
}
#Override
public void show()
{
for(T a : items)
{
if(a != null)
System.out.print(a+", ");
}
}
public T[] grow(T[] a)
{
T[] newA = (T[]) new Comparable[a.length+5];
System.arraycopy(a, 0, newA, 0, a.length);
return newA;
}
}
main
public class Main {
public static void main(String[] args) throws IOException
{
OrderSet<String> s1 = new OrderSet<>();
WordCount s2 = new WordCount();
Scanner input = new Scanner("the boy plays in the park with dog");
while (input.hasNext())
{
String w = input.next();
s1.add(w);
}
s1.show();
System.out.println();
}
}
I think it's your Sort Algorithm that is wrong. Ardentsonata is right, you use a Bubblesort algorithm but there is a mistake:
for (int i = 0; i < size-1; i++) {
for(int j = 1; j < size; j++){
T tmp;
if (items[i].compareTo(items[j]) > 0) {
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
The Problem is the start value of the second loop, you want to check if any other element - except the ones you already sorted is bigger than the element you want to sort at the moment.
So your second loop needs this head:
for(int j = (i+1); j < size; j++)
so you really sort the array.
Otherwise you were uncontrollable switching your values aroung, because after you switched something to the second slot you switch it back in the next iteration.
Hope that helps !
What you seem to be doing is a bubble sort as you add in items, the generic form of a selection sort is as follows:
for(int i = 0; i<arr.length - 1; i++)
{
int smallest = i;
for(int j = i + 1; j< arr.length; j++)
{
if(arr[j].compareTo(arr[smallest]) > 0)
smallest = j;
}
if(smallest < arr.length && smallest != i)
swap(arr[i], arr[smallest]);
}
You could do it swapping the largest into the last index, but this should work as well. Note, swap is just a placeholder psuedocode for the actual swapping.
Use java.util.TreeSet< T >, which implements SortedSet< T >.
It's better to use String compare concept in this case
class City {
public static void main (String args[])
{
int i,j;
String temp;
String s[] = new String[6];
for(i=0; i<6; i++)
s[i]=args[i];
for(i=0;i<6;i++){
for(j=0;j<6-i-1;j++){
if(s[j].compareTo(s[j+1])>0)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
for(i=0; i<6; i++)
{
System.out.println(s[i]);
}
}}
Related
Given the following code:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
break; //Preventing from counting duplicate times, is there way to replace this?
}
}
}
return count;
}
I would like to know if there is a solution which doesn't use break statement since I've heard its bad practice.
But without the break this method returns 6 instead of wanted 3 for array {'x', 'x', 'x'}.
If you're trying to find the number of unique elements in the array try using this approach as it has only one loop and hence efficient.
private static int findNUmberOfUnique(String[] array) {
Set<String> set=new HashSet<>();
for(int i=0;i<array.length;i++){
if(!set.contains(array[i])){
set.add(array[i]);
}
}
return set.size();
}
Let me know if I did not understand your requirement clearly.
You can always use a flag instead of break:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
boolean found = false;
for (int k = 0; k < a.length && !found; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
found = true;
}
}
}
return count;
}
You can use a hashmap to find the same elements in an array and preventing duplicate counting.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer>hs=new HashSet<Integer>();
for(int i:nums1)
hs.add(i);
HashSet<Integer>hs1=new HashSet<Integer>();
for(int j:nums2){
if(hs.contains(j)){
hs1.add(j);
}
}
int[] res=new int[hs1.size()];
int j=0;
for(int k:hs1)
res[j++]=k;
return res;
}
}
Hello I create a 2D array and i want to find the position from the first 2 in the array. And after to add the index in a new ArrayList. But this code doesn't work. Any idea for the problem?
import java.util.ArrayList;
class Test {
public static void main(String[] args) {
ArrayList<Integer> tableau = new ArrayList<Integer>();
int[][] tab = {
{1,1,1,1,1,1,2,1,1,2,1,1,1,2,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1},
};
for (int i = 0; i < tab.length; i++) {
int j = tab[i].indexOf(2);
for (int k = j ; k < tab[i].length; k++) {
if (tab[i][j] == 2){
tableau.add(j);
}
}
}
for (Integer row : tableau) {
System.out.println("row = "+ Arrays.toString(tableau));
}
}
}
As others have mentioned, regular arrays do not have an indexOf method, meaning that you will get an error when you compile.
However, you can easily create your own method to use as a substitute.
private static int indexOf(int value, int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] == value)
return i;
}
return -1;
}
Then you can just replace this line:
int j = tab[i].indexOf(2);
With this one:
int j = indexOf(2, tab[i]);
I got το code an array sort for exam preparing. I am already done, the only prob is that my minimum variable is not resetting it self. And I can't put it "null"
Maybe you got an idea... In the beginning I put min = c[0][0]; But if this is the smallest number. It won't work. :/
public class Sort {
public static void main(String[] args) {
int[] a = {3,2,-1,-2,-5,4};
specialSort(a);
}
static void specialSort(int[] a) {
try {
int[] b = new int[a.length];
int[][] c = new int[a.length][2];
for (int k = 0; k<a.length; k++) {
for (int l = 0; l<2; l++) {
if (l == 0) {
c[k][l] = a[k];
} else {
c[k][l] = 0;
}
}
}
int min, minindex;
for (int j=0; j<c.length; j++) {
for (int i=0; i<c.length; i++) {
if (c[i][1] == 0) {
min = c[i][0];
if (min > c[i][0]) {
min=c[i][0];
minindex = i;
}
}
}
b[j] = min;
c[minindex][1] = 1;
}
for(int i=0; i<c.length; ++i) {
//for(int j=0; j<2; j++) {
System.out.print(b[i]+" ");
System.out.println();
}
} catch (IllegalArgumentException e) {
System.out.println("dulli");
}
}
}
If I understand correctly what you're saying and what your problem is, why don't you try setting min initially to
Integer.MAX_VALUE
or
Long.MAX_VALUE
depending on the type of your data, so that you will replace it somehow with one of the numbers from your input, because for sure some number from your input will be smaller than the largest number java can represent? I think it should work if you do it this way
I need some help from the experts. I've got a task to find 2 duplicate elements in a 2d array and print out their indexes. Here's the code i've made. It creates a 2d array, then fill it manually from the keyboard. But now i have some problems with the method that finds and prints the duplicates. It prints FALSE if there are no duplicates, and TRUE if there are some. But I can't make it print out ALL the duplicates and its indexes. Please help me with this. Best regards
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import static java.lang.System.out;
public class Main {
public static void main(String[] args)
throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
out.println("Введите размерность массива n:");
int n = Integer.parseInt(reader.readLine());
out.println("Введите размерность массива m:");
int m = Integer.parseInt(reader.readLine());
int [][] a = new int [n][m];
out.println("Введите числа массива :");
int i,j;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt(reader.readLine());
}
}
out.println("Введенный массив : ");
for (i = 0; i < a.length; i++, out.println()) {
for (j = 0; j < a[i].length; j++) {
out.printf(" %4d", a[i][j]);
}
}
out.println(extra(a));
}
private static boolean extra(int[][] data) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (set.contains(data[i][j])) {
out.printf("[%d][%d] - %d\n", i, j, data[i][j]);
return true;
} else {
set.add(data[i][j]);
}
}
}
return false;
}
}
A general method for determining if any item in a collection satisfies a condition, while also processing every item, is:
boolean conditionSatisfied = false;
for each item in collection {
if item satisfies condition {
process item;
conditionSatisfied = true;
}
}
return conditionSatisfied;
I changed your method and used one boolean variable found..This will work
private static boolean extra(int[][] data) {
boolean found = false;
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (set.contains(data[i][j])) {
out.printf("[%d][%d] - %d\n", i, j, data[i][j]);
found = true;
} else {
set.add(data[i][j]);
}
}
}
return found;
}
I think I have done the selection sort but I am not sure. Is this really an implementation of selection sort?
static void selectionSort()
{
int min = Integer.MIN_VALUE;
int n = 0;
for(int I=0; I<arraySize; I++)
{
min = dataArray[I];
for(int j=I; j<n; j++)
{
if(dataArray[min]<dataArray[j])
{
min = j;
if(dataArray[min] < dataArray[I])
{
int temp = dataArray[I];
dataArray[I] = dataArray[min];
dataArray[min] = temp;
}
}
}
}
}
I'm not sure I understand how your algorithm works at all. Specifically, you do
min = dataArray[i];
and then later
dataArray[min]<dataArray[j]
i.e. you treat min both as a value in the array, and an index.
Selection sort works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list
(source)
The changes required for your code to accurately implement selection sort would be the following:
Change the inner loop to just find the index of the smallest element. Call it minIndex for instance.
Do the swapping after the inner loop. i.e., swap element at index I with minIndex.
Oh, and as DonCallisto points out in the comments, you may want to do n = dataArray.length instead of n = 0 :-)
public class SelectionSort {
/**
* #Author Chandrasekhara Kota
*/
public static void main(String[] args) {
int arr[]={9,1,8,5,7,-1,6,0,2,2718};
int sortedArr[]=selectionSort(arr);
for (int i = 0; i <sortedArr.length; i++)
{
System.out.println(sortedArr[i]);
}
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
}
Here is a selection sort implementation in java -
public class SelectionSort {
static int intArray[] = { 10, 5, 100, 1, 10000 };
public static void doSort() {
for (int outer = 0; outer < intArray.length; outer++) {
int minPosition=outer;
for(int inner=outer;inner<intArray.length;inner++){
if(intArray[inner]<intArray[minPosition]){
minPosition=inner;
}
}
int temp=intArray[minPosition];
intArray[minPosition]=intArray[outer];
intArray[outer]=temp;
}
}
public static void printArray() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(" " + intArray[i]);
}
}
public static void main(String args[]) {
System.out.print("Array Before Sorting->");
printArray();
doSort();
System.out.print("\nArray After Sorting ->");
printArray();
}
}
The above code is picked from - http://www.javabrahman.com/algorithms-in-java/selection-sort-in-java/. This link has detailed explanation on the working of the above code just in case you need the same.