Cs Problem Set Answers
Autor: Maryam • January 7, 2018 • 730 Words (3 Pages) • 748 Views
...
public static void print(Comparable[] x)
{
for(int j = 0; j
{
System.out.print(x[j] + " ");
}
System.out.println();
}
}
---------------------------------------------------------------
//sorting Comparable
public class Sort2
{
public static void main(String[] asd)
{
String[] x = {"liz", "chichi", "kim", "shashi" , "angel", "han", "hano"};
sort(x);
print(x);
System.out.println();
}
public static void sort(Comparable[] x)
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(int j = 1; j
{
if(x[j-1].compareTo(x[j]) > 0)//polymorphism dictates that compareTo of String lcass
{
Comparable temp = x[j-1];
x[j-1] = x[j];
x[j] = temp;
sorted = false;
}
}
}
}
public static void print(Comparable[] x)
{
for(int j = 0; j
{
System.out.print(x[j] + " ");
}
System.out.println();
}
}
//finds sum of diagonal elements
public class Trace
{
public static void main(String[] asd)
{
int[][] x = { {1,2,3}, {4,5,6}, {7,8,9}};
int num = trace(x);
System.out.println("Trace is " + num);
}
public static int trace(int[][] x)
{
int sum = 0;
for(int r = 0; r
{
sum = sum + x[r][r];
}
return sum;
}
}
//insert increasing ints in an arry
public class Trivial
{
public static void main(String[] asd)
{
final int DIM = 3;
int[][] x = new int[DIM][DIM];
increase(x);
print(x);
System.out.println();
}
public static void print(int[][] x)
{
for(int r = 0; r
{
for(int c = 0; c
{
System.out.printf(" %d", x[r][c]);
}
System.out.println();
}
}
public static void increase(int[][] x)
{
int n = 0;
for(int r = 0; r
{
for(int c = 0; c
{
n++;
x[r][c] = n;
}
}
}
}
//insert increasing ints in an arry
public class Trivial2
{
public static void main(String[] asd)
{
final int DIM = 3;
int[][] x = new int[DIM][DIM];
increase(x);
print(x);
System.out.println();
}
public static void print(int[][] x)
{
for(int r = 0; r
...