I'm having a school project for Java and I'm assigned too. Now I'm having an issue with a part of the project which I can't figure out.
The application must generate all possible word combinations (can be verified via a dictionary) from a two-dimensional char array (char[][] board). The board is dynamic as the user can choose the scale: 4x4, 5x5, 4x5, 5x4, 4x6, ... So I guess a nested loop wouldn't be approriate here, correct me if I'm wrong. Words must be generated horizontally, verticaly and diagonally. Example of a 4x4 board:
| u | a | u | s |
| n | n | i | i |
| a | o | e | b |
| e | u | e | z |
Code was completely wrong.
Another idea may be to brute force every possible path on the board and then try those saved paths to verify whether it's a word or not.
Thanks in advance!
One way to solve this is:
for each path on the board
if corresponding word in dictionary
print it
To find all paths, you could adapt any graph traversal algorithm.
Now this will be really slow, because there are a great many paths of a board that size (for a board with n cells, we can have at most n * 4 ^ (n - 1) paths, so for a 5 by 5 board, you'd have something like 25 * 2 ^ 50 ~= 10^16 paths.
One way to improve on this is to interleave traversing the graph and checking the dictionary, aborting if the current path's word is not a prefix of a dictionary word:
class Board {
char[][] ch;
boolean[][] visited;
Trie dictionary;
void find() {
StringBuilder prefix = new StringBuilder();
for (int x = 0; x < maxx; x++) {
for (int y = 0; y < maxy; y++) {
walk(x, y, prefix);
}
}
}
void walk(int x, int y, StringBuilder prefix) {
if (!visited[x][y]) {
visited[x][y] = true;
prefix.append(ch[x][y]);
if (dictionary.hasPrefix(prefix)) {
if (dictionary.contains(prefix)) {
System.out.println(prefix);
}
int firstX = Math.max(0, x - 1);
int lastX = Math.min(maxx, x + 1);
int firstY = Math.max(0, y - 1);
int lastY = Math.min(maxy, y + 1);
for (int ax = firstX; ax <= lastX; ax++) {
for (int ay = firstY; ay <= lastY; ay++) {
walk(ax, ay, prefix);
}
}
}
prefix.setLength(prefix.length() - 1);
visited[x][y] = false;
}
}
As you can see, the method walk invokes itself. This technique is known as recursion.
That leaves the matter of finding a data structure for the dictionary that supports efficient prefix queries. The best such data structure is a Trie. Alas, the JDK does not contain an implementation, but fortunately, writing one isn't hard.
Note: The code in this answer has not been tested.
A fairly straightforward way of conceptualizing this is to apply a breadth-first search (BFS) approach to each position (or depth-first, depending upon which tweaks you might later want to make). This would give you all possible letter combinations, up to a level of characters equal to the max depth of the search. Depending on your requirements, such as the longest allowed word, max running time, and if a dictionary is provided via a data structure or file, this may be the key part.
Or, you may need to optimize quite a bit more. If so, consider how you might expedite either a BFS or DFS. What if you did a DFS, but knew three characters in that no word starts with "zzz"? You could shave a lot of time off by not having to traverse all conceivable orderings. To look words up effectively, you might need to make further adjustments. But I'd start with Java's built-in functionality (String.startsWith() comes to mind in this instance), measure performance (perhaps with a limited max word length), and then optimize when and where it's needed.
Start by turning rows , columns and diagonals to Strings, using a simple repetitive method. Then , I would turn it into a StringBuilder or in order to check which words are real and eliminate those which aren't directly from the StringBuilder. then , just print it to a String.There are a lot of useful tools to eliminate or replace words in java.
Related
Problem 15:
Starting in the top left corner of a 2×2 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 20×20 grid?
So my attempt at Problem 15 is kinda bruteforcy because I try to get permutations of all of the possible valid paths by going from right to left and changing the predecessor of the first change of direction. For example, when I have a 2x2 grid (look at the Problem 15 link graphics) the first path I'll take is right - right - down - down and the last one I'll take is down - down - right - right, which is also my termination criteria. I add the possible valid paths into a list and also use that list to determine whether the valid path has been already added or not. And to permutate a path I'll do what I've mentioned earlier: I go from right to left in my array (Which in the graphic would be the bottom right corner where the arrowhead points at) and change the first element of which the next element is different from itself. So right - right - down - down would become right - right - right - down, which is obviously invalid since you have to have the same amount of rights and downs to be able to reach the end corner. So what I thought is to make another loop going from left to right and change as many elements as needed to get a valid path. So in this example right - right - right - down becomes down - right - right - down.
Also, what I forgot is that I'm not counting the points, I'm counting the edges from top left corner to bottom right corner.
So I have already written some code, but it doesn't work at all.
package projecteuler;
import java.util.ArrayList;
public class Projecteuler {
public static final int GRIDSIZE = 2;
public static void main(String[] args) {
ArrayList<boolean[]> paths = new ArrayList<>();
paths.add(new boolean[GRIDSIZE * 2]);
for(int i = 0; i < GRIDSIZE; i++) {
paths.get(0)[i] = true;
paths.get(0)[GRIDSIZE * 2 - 1 - i] = false;
}
boolean[] buf = paths.get(0).clone();
printArr(buf);
boolean tmp;
while(!checkTerminate(paths)) {
while(paths.contains(buf)) {
tmp = buf[buf.length - 1];
for(int i = buf.length - 1; buf[i - 1] != tmp && 0 < i; i--) {
buf[i] = !buf[i];
for(int j = 0; checkValid(buf) && j < i; j++)
buf[j] = !buf[j];
}
}
paths.add(buf.clone());
printArr(buf);
}
System.out.println(paths.size());
}
public static boolean checkTerminate(ArrayList<boolean[]> paths) {
boolean[] endPath = new boolean[GRIDSIZE * 2];
for(int i = 0; i < GRIDSIZE; i++) {
endPath[i] = false;
endPath[GRIDSIZE * 2 - 1 - i] = true;
}
return paths.contains(endPath);
}
public static boolean checkValid(boolean[] arr) {
int countR = 0,
countL = 0;
for(int i = 0; i < arr.length; i++)
if(arr[i])
countR++;
else
countL++;
return countR == countL;
}
public static void printArr(boolean[] arr) {
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] ? "right " : "down ");
System.out.println();
}
}
It somehow doesn't change anything anywhere.
right right down down
right right down down
right right down down
right right down down ...
and so on is all it's outputting. It seems that the code simply doesn't permutate my path, but also doesn't get stuck in any of the for loops. My best guess would be that my function criteria are placed in the wrong sequence
I also thought of a solution with backtracking like we did for a labyrinth two years ago in school, but I want to see if this approach is anywhere viable or not before redoing everything.
EDIT:
I'll try to implement the images of the 2 x 2 grid example asap, but the ProjectEuler website is under maintainance at the moment.
The solution is given by the number of combinations of "down" and "right" movements we can have. Since there is no backtracking, there are N downwards and N rightwards movements in total (in any route, for an NxN grid). There are 2N movements in total.
We can obtain this using the binomial coefficient, nCr (pronounced "n choose r"), which is the number of ways of choosing r objects from n objects (each of which can be two things). In our case an "object" is either a downward or rightward movement. This is given by
Thus the number we want is:
For N = 2 this gives 6. For N = 20 this gives 137846528820.
Let a step in right be termed as R and a step down is termed as D.
In order to reach from top-left to bottom-right on a n rows and m column grid, you will have to go right m times and go down n times.
Essentially, you will have to get all the possible arrangements of m R's and n D's.
Example: For a 2 by 2 grid, the number of unique permutations of the word RRDD will be the number of ways in which you can go, viz.
RRDD
RDRD
DRDR
DDRR
Google the formula to calculate the permutations of letters with repetition, which is given by:
n! / ( r1! * r2! ... ), where sum of all r's is n.
This question on Math SE pops up first when looking for repetitive letter permutation count, and the second answer explains better in my opinion.
So, to return the count AND even to return the paths, you don't need to traverse the maze at all. Just do the formula calculation for first one and print the permutations for second problem.
Giving the paths when certain steps are off grid will be the only case that requires you to actually traverse the maze.
UPDATE:
It helps to visualize the formula for permutation of repeated letters.
Here is a slide that demonstrates that case. See how the 2 E's end up duplicating the arrangements when generating the permutations. In general, any letter that's repeated r times will cause r! duplication because wherever in the arrangement that letter is put, it can be replaced with another same letter without giving a new permutation.
That way, if we divide the total n! permutations with r!, we get the actual unique permutations.
Image Source
I'm trying to create an algorithm which determines whether or not all of the rows in a 2D array of integers are unique (i.e. disjoint). Currently, I have a brute force algorithm which checks each value in each row to each value in the other rows, but I'd like to speed this up. Is there some kind of divide and conquer method to handle this? I have found some semi-solutions for this in single arrays and lists, but not in 2d arrays.
If you want to check whether there are two rows that contain the same number, you can put all the numbers along with numbers of rows that they belong to into one long list. Then sort this list which will make all the identical numbers stand next to each other. Than you can easily determine for each cluster of identical numbers whether they originally belonged to the same row or not.
If your table is n × m, the algorithm will run in O(nm × (log(n) + log(m))).
To test whether any two rows are disjoint**, make two sets (like java sets that reject duplicates and do so in almost O(1) time), one for each row and count the elements of each.
The two rows are disjoint if:
count(rowASet) + count(rowBSet) == count( union(rowASet, rowBSet) )
This suggests an algorithm for a 2D array where a rows are successively added (as sets) to a running total set. The count of the total set is measured before and after the addition of each row's set. If that count increases by the size of the row set just added, then the row just added is disjoint from those added so far.
**See the conversation with #CandiedOrange. I'm taking "disjoint row" to mean a row that contains no element found in any other row, but might itself contain repeated elements internally.
EDIT: my answer was slow and stupid. Or to put it more kindly, it was doing unnecessary work because it computed which two rows intersect instead of whether or not any two rows intersect.
After I posted I thought of 2 faster algorithms but they turned out to be Danylo Mysak's answer and the "running total set" danh hinted at.
I would still like to benchmark these different approaches.
If you are allowed to use java collections consider using java's HashSet. It was designed for things like this:
areDisjoint() inspired by http://www.geeksforgeeks.org/check-two-given-sets-disjoint/
import java.util.*;
public static void main (String[] args)
{
int[][] twoD = {{3,3,3},{4,4,4},{5,5,5}};
if ( disjointRows(twoD) )
{
System.out.println("Mutually disjoint rows");
}
else
{
System.out.println("Some element duplicated in other row");
}
}
public static boolean disjointRows(int[][] twoD)
{
// -- Copy 2D array into data structure -- //
ArrayList<HashSet<Integer>> rows = new ArrayList<HashSet<Integer>>();
for (int[] row : twoD)
{
HashSet<Integer> hs = new HashSet<Integer>();
for (int elem : row)
{
hs.add(elem);
}
rows.add( hs );
}
// Above is O = r*c time just as it would be to copy the 2D array.
// or you can express it as O(n^2)
// -- Mutual disjoint rows test -- //
// Compare every combination of rows
for (int y=1; y< rows.size(); y++)
{
for (int x=0; x<y; x++)
{
//TODO remove debugging code
System.out.print(areDisjoint( rows.get(x), rows.get(y) ) );
System.out.print("=");
System.out.print("(" + x + "," + y + ") ");
if (! areDisjoint( rows.get(x), rows.get(y) ) )
{
return false;
}
}
System.out.println("");
}
return true;
//Above is O = r(r-1)/2 * c
//or you can express it as O(n^3)
}
static boolean areDisjoint(Set<Integer> set1, Set<Integer> set2)
{
//set1 must not contain anything in set2
for (int i : set2)
{
if ( set1.contains(i) )
return false;
}
return true;
// Above is c or O(n) because contains lookup is O(1)
}
Output:
// true=(0,1)
// true=(0,2) true=(1,2)
// Mutually disjoint rows
I can't tell if this is better than your "brute force" solution since you didn't post it.
I can tell from a big O notation perspective this is neck and neck with japreiss's solution. We're both at O(n^3). This solution uses more memory because it copies the 2D array rather than mutate it. When performance is equal I strongly urge you to pick your algorithm based on readability. I admit mine is longer. I took the time to comment it.
See also: Is a Java hashmap really O(1)?
// If each row is to be disjoint from all other rows then
// then testing them all against each other would produce
// this truth table.
//
// 0 1 2
// |----|----|----|
// 0 | F | T | T |
// |----|----|----|
// 1 | T | F | T |
// |----|----|----|
// 2 | T | T | F |
// |----|----|----|
//
// Testing a row against it self can be ignored as can
// tests that simply transpose the input rows. Leaving us with
//
// 0 1 2
// |
// 0 |
// |----|
// 1 | T |
// |----|----|
// 2 | T | T |
// |----|----|
//
// So long as that's true, the rows are mutually disjoint
I have created TicTacToe game. I use minmax algorithm.
When the board is 3x3 I just calculate every possible move for a game till the end and -1 for loss, 0 for tie, 1 for win.
When it comes to 5x5 it can't be done(to many options(like 24^24) so I have created evaluation method which gives: 10^0 for one CIRCLE inline, 10^1 for 2 CIRCLE inline, ..., 10^4 for 5 CIRCLES inline, but it is useless.
Does anybody have better idea for assesment?
Example:
O|X|X| | |
----------
|O| | | |
----------
X|O| | | |
----------
| | | | |
----------
| | | | |
Evaluation -10, 2 circles across once and inline once (+200), 2 crosses inline(-100), and -1 three times and + 1 three times for single cross and circle.
This is my evaluation method now:
public void setEvaluationForBigBoards() {
int evaluation = 0;
int howManyInLine = board.length;
for(; howManyInLine > 0; howManyInLine--) {
evaluation += countInlines(player.getStamp(), howManyInLine);
evaluation -= countInlines(player.getOppositeStamp(), howManyInLine);
}
this.evaluation = evaluation;
}
public int countInlines(int sign, int howManyInLine) {
int points = (int) Math.pow(10, howManyInLine - 1);
int postiveCounter = 0;
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
//czy od tego miejsca jest cos po przekatnej w prawo w dol, w lewo w dol, w dol, w prawo
if(toRigth(i, j, sign, howManyInLine))
postiveCounter++;
if(howManyInLine > 1) {
if(toDown(i, j, sign, howManyInLine))
postiveCounter++;
if(toRightDiagonal(i, j, sign, howManyInLine))
postiveCounter++;
if(toLeftDiagonal(i, j, sign, howManyInLine))
postiveCounter++;
}
}
}
return points * postiveCounter;
}
Number of options (possible sequences of moves) after the first move is 24! and not 24^24. It is still a too much high
number so it is correct to implement an heuristic.
Note that answers about good heuristics are necessarily based on the opinion of the writer so I give my opinion but to find
out what is "the best heuristic" you should make the various ideas playing one against the other in the following way:
take the two heuristics A and B that you want to compare
generate at random a starting configuration
let A play with O and B play with X
from the same starting configuration let A play with X and B play with O
take stats of which one wins more
Now my thoughts about good possible heuristics starting points for an nxn playfield with winning sequence length of n:
since the winning condition for a player it to form a straight sequence of its marks my idea is to use as base values the number of possibilities that each player has still available to built such a straight sequence.
in an empty field both O and X have ideally the possibility to realize the winning sequence in several ways:
horizontal possibilities: n
vertical possibilities: n
diagonal possibilities: 2
total possibilities: 2n+2
in the middle of a round the number of remaining opportunities for a player are calculated as: "the number of rows without opponent's marks + the number of columns without opponent's marks + the number of diagonals without opponent's marks.
instead than calculate all each time it can be considered that:
after a move of one player the umber of still available possibilities are:
unchanged for him
equal or lowered for the opponent (if the mark has been placed in a row/col/diagonal where no marks had already been placed by the considered player)
as heuristic i can propose -
is possible that - k * with k > 1 give better results and in the end this can be related to how a draw is considered with regard to a lose.
One side consideration:
playfield cells are n^2
winning possibilities are 2n+2 if we keep the winning length equal to the field edge size
this give me the idea that the more the size is increased the less interesting is to play because the probability of a draw after a low number of moves (with reference to the playfield area) becomes higher and higher.
for this reason I think that the game with a winning length lower that n (for example 3 independently from the playfield size) is more interesting.
Named l the wining length we have that the number of possibilities is 2*((n+1-l)*(2n+1-l)) = O(n^2) and so well proportioned with the field area.
I have just started my long path to becoming a better coder on CodeChef. People begin with the problems marked 'Easy' and I have done the same.
The Problem
The problem statement defines the following -:
n, where 1 <= n <= 10^9. This is the integer which Johnny is keeping secret.
k, where 1 <= k <= 10^5. For each test case or instance of the game, Johnny provides exactly k hints to Alice.
A hint is of the form op num Yes/No, where -
op is an operator from <, >, =.
num is an integer, again satisfying 1 <= num <= 10^9.
Yes or No are answers to the question: Does the relation n op num hold?
If the answer to the question is correct, Johnny has uttered a truth. Otherwise, he is lying.
Each hint is fed to the program and the program determines whether it is the truth or possibly a lie. My job is to find the minimum possible number of lies.
Now CodeChef's Editorial answer uses the concept of segment trees, which I cannot wrap my head around at all. I was wondering if there is an alternative data structure or method to solve this question, maybe a simpler one, considering it is in the 'Easy' category.
This is what I tried -:
class Solution //Represents a test case.
{
HashSet<SolutionObj> set = new HashSet<SolutionObj>(); //To prevent duplicates.
BigInteger max = new BigInteger("100000000"); //Max range.
BigInteger min = new BigInteger("1"); //Min range.
int lies = 0; //Lies counter.
void addHint(String s)
{
String[] vals = s.split(" ");
set.add(new SolutionObj(vals[0], vals[1], vals[2]));
}
void testHints()
{
for(SolutionObj obj : set)
{
//Given number is not in range. Lie.
if(obj.bg.compareTo(min) == -1 || obj.bg.compareTo(max) == 1)
{
lies++;
continue;
}
if(obj.yesno)
{
if(obj.operator.equals("<"))
{
max = new BigInteger(obj.bg.toString()); //Change max value
}
else if(obj.operator.equals(">"))
{
min = new BigInteger(obj.bg.toString()); //Change min value
}
}
else
{
//Still to think of this portion.
}
}
}
}
class SolutionObj //Represents a single hint.
{
String operator;
BigInteger bg;
boolean yesno;
SolutionObj(String op, String integer, String yesno)
{
operator = op;
bg = new BigInteger(integer);
if(yesno.toLowerCase().equals("yes"))
this.yesno = true;
else
this.yesno = false;
}
#Override
public boolean equals(Object o)
{
if(o instanceof SolutionObj)
{
SolutionObj s = (SolutionObj) o; //Make the cast
if(this.yesno == s.yesno && this.bg.equals(s.bg)
&& this.operator.equals(s.operator))
return true;
}
return false;
}
#Override
public int hashCode()
{
return this.bg.intValue();
}
}
Obviously this partial solution is incorrect, save for the range check that I have done before entering the if(obj.yesno) portion. I was thinking of updating the range according to the hints provided, but that approach has not borne fruit. How should I be approaching this problem, apart from using segment trees?
Consider the following approach, which may be easier to understand. Picture the 1d axis of integers, and place on it the k hints. Every hint can be regarded as '(' or ')' or '=' (greater than, less than or equal, respectively).
Example:
-----(---)-------(--=-----)-----------)
Now, the true value is somewhere on one of the 40 values of this axis, but actually only 8 segments are interesting to check, since anywhere inside a segment the number of true/false hints remains the same.
That means you can scan the hints according to their ordering on the axis, and maintain a counter of the true hints at that point.
In the example above it goes like this:
segment counter
-----------------------
-----( 3
--- 4
)-------( 3
-- 4
= 5 <---maximum
----- 4
)----------- 3
) 2
This algorithm only requires to sort the k hints and then scan them. It's near linear in k (O(k*log k), with no dependance on n), therefore it should have a reasonable running time.
Notes:
1) In practice the hints may have non-distinct positions, so you'll have to handle all hints of the same type on the same position together.
2) If you need to return the minimum set of lies, then you should maintain a set rather than a counter. That shouldn't have an effect on the time complexity if you use a hash set.
Calculate the number of lies if the target number = 1 (store this in a variable lies).
Let target = 1.
Sort and group the statements by their respective values.
Iterate through the statements.
Update target to the current statement group's value. Update lies according to how many of those statements would become either true or false.
Then update target to that value + 1 (Why do this? Consider when you have > 5 and < 7 - 6 may be the best value) and update lies appropriately (skip this step if the next statement group's value is this value).
Return the minimum value for lies.
Running time:
O(k) for the initial calculation.
O(k log k) for the sort.
O(k) for the iteration.
O(k log k) total.
My idea for this problem is similar to how Eyal Schneider view it. Denoting '>' as greater, '<' as less than and '=' as equals, we can sort all the 'hints' by their num and scan through all the interesting points one by one.
For each point, we keep in all the number of '<' and '=' from 0 to that point (in one array called int[]lessAndEqual), number of '>' and '=' from that point onward (in one array called int[]greaterAndEqual). We can easily see that the number of lies in a particular point i is equal to
lessAndEqual[i] + greaterAndEqual[i + 1]
We can easily fill the lessAndEqual and greaterAndEqual arrays by two scan in O(n) and sort all the hints in O(nlogn), which result the time complexity is O(nlogn)
Note: special treatment should be taken for the case when the num in hint is equals. Also notice that the range for num is 10^9, which require us to have some forms of point compression to fit the array into the memory
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In-place transposition of a matrix
Recently attended an Technical Written Interview. Came through the following question.
I have an array as say
testArray = {a1,a2,a3,...an,b1,b2,b3,....bn,c1,c2,c3,.....,cn}
I need to sort this array as `
testArray = {a1,b1,c1,a2,b2,c2,a3,b3,c3,.....,an,bn,cn}
Constraint is I should not use extra memory, should not use any inbuilt function.
Should write complete code, it can be in any language and can also use any data structure.
eg:
Input: {1,2,3,4,5,6,7,8,9}, n = 3
Output: {1,4,7,2,5,8,3,6,9}
I could not get any solution within the constraint, can anyone provide solution or suggestion?
This is just a matrix transpose operation. And there is even a problem and solution for in-place matrix transposition on Wikipedia.
No extra space is impossible, since you need to at least go through the array. O(1) additional memory is possible, with heavy penalty on the time complexity.
The solution is built on follow-the-cycle algorithm in the Wikipedia page: for each cell, we will find the cell with the smallest index in the cycle. If the cell with the smallest index is greater than or equal (>=) to the index of the current cell, we will perform chain swapping. Otherwise, we ignore the cell, since it has been swapped correctly. The (loosely analyzed) upper bound on time complexity can go as high as O((MN)2) (we go through M * N cells, and the cycle can only be as long as the total number of cells).
Impossibility
It is impossible to implement this algorithm without extra use of memory and an arbitrary length because you need a an iterator to traverse the list and that takes up space.
Finding the right indices to swap
For fixed lengths of the array and fixed n you can use a matrix transpose algorithm.
and in order to swap the elements y
The algorithm you are looking for is a matrix transpose algorithm.
so you have to swap every element exactly once iterating through it.
http://en.wikipedia.org/wiki/Transpose
basically you have to swap the m -th element in the n - th component with the n - th element in the m -th component. This can be done by a double loop.
m = length(array)/n;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
index_1 = i * m + j;
index_2 = j * m + i
swap(index_1, index_2);
}
Note: For fixed m and n this loop can be completely unrolled and therefore m, i, j can be replaced by a constant.
Swaping without Memory consumption
In order to swap every element without using extra space you can use the XOR swap algorithm as pointed out in the comments:
X := X XOR Y
Y := Y XOR X
X := X XOR Y
The simplest way to swap two numbers (a and b) without using a temporary variable is like this:
b = b + a;
a = b - a;
b = b - a;
If you write that in a function, then you're part of the way there. How you keep track of which variable to swap within the arrays without using a temporary variable eludes me right now.
Bear in mind voters: he doesn't actually need to sort the array, just swap the right values.
Edit: this will work with large values in Java (and in C/C++ unless you turn on some very aggressive compiler optimisations - the behaviour is undefined but defaults to sane). The values will just wrap around.
Second edit - some (rather untested) code to flip the array around, with I think 4 integers over the memory limit. It's while technically massively unthreadsafe, but it would be parallelisable just because you only access each array location once at most:
static int[] a = {1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16};
static int n = 4;
public static void main(String[] args)
{
for(int i = 0; i < a.length/n; i++) // 1 integer
for(int j = 0; j < n; j++) // 1 integer
if(j > i)
swap(i*n+j, j*n+i);
}
static void swap(int aPos, int bPos) // 2 integers
{
if(a[aPos] != a[bPos])
{
a[bPos] = a[aPos] + a[bPos];
a[aPos] = a[bPos] - a[aPos];
a[bPos] = a[bPos] - a[aPos];
}
}
Apologies if this misunderstands the question; I read it carefully and couldn't work out what was needed other than this.
Take a look at Quicksort algorithm
For more information about available algorithms, go to Sorting algorithm page.