cern.colt.function.IntComparator Java Examples

The following examples show how to use cern.colt.function.IntComparator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
Sorts the matrix slices into ascending order, according to the <i>natural ordering</i> of the matrix values in the given <tt>[row,column]</tt> position.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort by other dimensions, use dice views. To sort descending, use flip views ...
<p>
The algorithm compares two 2-d slices at a time, determinining whether one is smaller, equal or larger than the other.
Comparison is based on the cell <tt>[row,column]</tt> within a slice.
Let <tt>A</tt> and <tt>B</tt> be two 2-d slices. Then we have the following rules
<ul>
<li><tt>A &lt;  B  iff A.get(row,column) &lt;  B.get(row,column)</tt>
<li><tt>A == B iff A.get(row,column) == B.get(row,column)</tt>
<li><tt>A &gt;  B  iff A.get(row,column) &gt;  B.get(row,column)</tt>
</ul>

@param matrix the matrix to be sorted.
@param row the index of the row inducing the order.
@param column the index of the column inducing the order.
@return a new matrix view having slices sorted by the values of the slice view <tt>matrix.viewRow(row).viewColumn(column)</tt>.
		<b>Note that the original matrix is left unaffected.</b>
@throws IndexOutOfBoundsException if <tt>row < 0 || row >= matrix.rows() || column < 0 || column >= matrix.columns()</tt>.
*/
public ObjectMatrix3D sort(ObjectMatrix3D matrix, int row, int column) {
	if (row < 0 || row >= matrix.rows()) throw new IndexOutOfBoundsException("row="+row+", matrix="+Formatter.shape(matrix));
	if (column < 0 || column >= matrix.columns()) throw new IndexOutOfBoundsException("column="+column+", matrix="+Formatter.shape(matrix));

	int[] sliceIndexes = new int[matrix.slices()]; // indexes to reorder instead of matrix itself
	for (int i=sliceIndexes.length; --i >= 0; ) sliceIndexes[i] = i;

	final ObjectMatrix1D sliceView = matrix.viewRow(row).viewColumn(column);
	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			Comparable av = (Comparable) (sliceView.getQuick(a));
			Comparable bv = (Comparable) (sliceView.getQuick(b));
			int r = av.compareTo(bv);
			return r<0 ? -1 : (r>0 ? 1 : 0);
		}
	};

	runSort(sliceIndexes,0,sliceIndexes.length,comp);

	// view the matrix according to the reordered slice indexes
	// take all rows and columns in the original order
	return matrix.viewSelection(sliceIndexes,null,null);
}
 
Example #2
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
Sorts the matrix slices into ascending order, according to the <i>natural ordering</i> of the matrix values in the given <tt>[row,column]</tt> position.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort by other dimensions, use dice views. To sort descending, use flip views ...
<p>
The algorithm compares two 2-d slices at a time, determinining whether one is smaller, equal or larger than the other.
Comparison is based on the cell <tt>[row,column]</tt> within a slice.
Let <tt>A</tt> and <tt>B</tt> be two 2-d slices. Then we have the following rules
<ul>
<li><tt>A &lt;  B  iff A.get(row,column) &lt;  B.get(row,column)</tt>
<li><tt>A == B iff A.get(row,column) == B.get(row,column)</tt>
<li><tt>A &gt;  B  iff A.get(row,column) &gt;  B.get(row,column)</tt>
</ul>

@param matrix the matrix to be sorted.
@param row the index of the row inducing the order.
@param column the index of the column inducing the order.
@return a new matrix view having slices sorted by the values of the slice view <tt>matrix.viewRow(row).viewColumn(column)</tt>.
		<b>Note that the original matrix is left unaffected.</b>
@throws IndexOutOfBoundsException if <tt>row < 0 || row >= matrix.rows() || column < 0 || column >= matrix.columns()</tt>.
*/
public DoubleMatrix3D sort(DoubleMatrix3D matrix, int row, int column) {
	if (row < 0 || row >= matrix.rows()) throw new IndexOutOfBoundsException("row="+row+", matrix="+Formatter.shape(matrix));
	if (column < 0 || column >= matrix.columns()) throw new IndexOutOfBoundsException("column="+column+", matrix="+Formatter.shape(matrix));

	int[] sliceIndexes = new int[matrix.slices()]; // indexes to reorder instead of matrix itself
	for (int i=sliceIndexes.length; --i >= 0; ) sliceIndexes[i] = i;

	final DoubleMatrix1D sliceView = matrix.viewRow(row).viewColumn(column);
	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			double av = sliceView.getQuick(a);
			double bv = sliceView.getQuick(b);
			if (av!=av || bv!=bv) return compareNaN(av,bv); // swap NaNs to the end
			return av<bv ? -1 : (av==bv ? 0 : 1);
		}
	};

	runSort(sliceIndexes,0,sliceIndexes.length,comp);

	// view the matrix according to the reordered slice indexes
	// take all rows and columns in the original order
	return matrix.viewSelection(sliceIndexes,null,null);
}
 
Example #3
Source File: Sorting.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
Sorts the matrix slices into ascending order, according to the <i>natural ordering</i> of the matrix values in the given <tt>[row,column]</tt> position.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort by other dimensions, use dice views. To sort descending, use flip views ...
<p>
The algorithm compares two 2-d slices at a time, determinining whether one is smaller, equal or larger than the other.
Comparison is based on the cell <tt>[row,column]</tt> within a slice.
Let <tt>A</tt> and <tt>B</tt> be two 2-d slices. Then we have the following rules
<ul>
<li><tt>A &lt;  B  iff A.get(row,column) &lt;  B.get(row,column)</tt>
<li><tt>A == B iff A.get(row,column) == B.get(row,column)</tt>
<li><tt>A &gt;  B  iff A.get(row,column) &gt;  B.get(row,column)</tt>
</ul>

@param matrix the matrix to be sorted.
@param row the index of the row inducing the order.
@param column the index of the column inducing the order.
@return a new matrix view having slices sorted by the values of the slice view <tt>matrix.viewRow(row).viewColumn(column)</tt>.
		<b>Note that the original matrix is left unaffected.</b>
@throws IndexOutOfBoundsException if <tt>row < 0 || row >= matrix.rows() || column < 0 || column >= matrix.columns()</tt>.
*/
public DoubleMatrix3D sort(DoubleMatrix3D matrix, int row, int column) {
	if (row < 0 || row >= matrix.rows()) throw new IndexOutOfBoundsException("row="+row+", matrix="+Formatter.shape(matrix));
	if (column < 0 || column >= matrix.columns()) throw new IndexOutOfBoundsException("column="+column+", matrix="+Formatter.shape(matrix));

	int[] sliceIndexes = new int[matrix.slices()]; // indexes to reorder instead of matrix itself
	for (int i=sliceIndexes.length; --i >= 0; ) sliceIndexes[i] = i;

	final DoubleMatrix1D sliceView = matrix.viewRow(row).viewColumn(column);
	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			double av = sliceView.getQuick(a);
			double bv = sliceView.getQuick(b);
			if (av!=av || bv!=bv) return compareNaN(av,bv); // swap NaNs to the end
			return av<bv ? -1 : (av==bv ? 0 : 1);
		}
	};

	runSort(sliceIndexes,0,sliceIndexes.length,comp);

	// view the matrix according to the reordered slice indexes
	// take all rows and columns in the original order
	return matrix.viewSelection(sliceIndexes,null,null);
}
 
Example #4
Source File: Sorting.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
Sorts the matrix slices into ascending order, according to the <i>natural ordering</i> of the matrix values in the given <tt>[row,column]</tt> position.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort by other dimensions, use dice views. To sort descending, use flip views ...
<p>
The algorithm compares two 2-d slices at a time, determinining whether one is smaller, equal or larger than the other.
Comparison is based on the cell <tt>[row,column]</tt> within a slice.
Let <tt>A</tt> and <tt>B</tt> be two 2-d slices. Then we have the following rules
<ul>
<li><tt>A &lt;  B  iff A.get(row,column) &lt;  B.get(row,column)</tt>
<li><tt>A == B iff A.get(row,column) == B.get(row,column)</tt>
<li><tt>A &gt;  B  iff A.get(row,column) &gt;  B.get(row,column)</tt>
</ul>

@param matrix the matrix to be sorted.
@param row the index of the row inducing the order.
@param column the index of the column inducing the order.
@return a new matrix view having slices sorted by the values of the slice view <tt>matrix.viewRow(row).viewColumn(column)</tt>.
		<b>Note that the original matrix is left unaffected.</b>
@throws IndexOutOfBoundsException if <tt>row < 0 || row >= matrix.rows() || column < 0 || column >= matrix.columns()</tt>.
*/
public ObjectMatrix3D sort(ObjectMatrix3D matrix, int row, int column) {
	if (row < 0 || row >= matrix.rows()) throw new IndexOutOfBoundsException("row="+row+", matrix="+Formatter.shape(matrix));
	if (column < 0 || column >= matrix.columns()) throw new IndexOutOfBoundsException("column="+column+", matrix="+Formatter.shape(matrix));

	int[] sliceIndexes = new int[matrix.slices()]; // indexes to reorder instead of matrix itself
	for (int i=sliceIndexes.length; --i >= 0; ) sliceIndexes[i] = i;

	final ObjectMatrix1D sliceView = matrix.viewRow(row).viewColumn(column);
	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			Comparable av = (Comparable) (sliceView.getQuick(a));
			Comparable bv = (Comparable) (sliceView.getQuick(b));
			int r = av.compareTo(bv);
			return r<0 ? -1 : (r>0 ? 1 : 0);
		}
	};

	runSort(sliceIndexes,0,sliceIndexes.length,comp);

	// view the matrix according to the reordered slice indexes
	// take all rows and columns in the original order
	return matrix.viewSelection(sliceIndexes,null,null);
}
 
Example #5
Source File: DataManager.java    From arx with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the order of the given sensitive attribute in the original dataset. 
 * Required for t-closeness.
 * 
 * @param attribute
 * @return distribution
 */
public int[] getOrder(String attribute) {

    // Prepare
    final int index = dataAnalyzed.getIndexOf(attribute);
    final String[] dictionary = dataAnalyzed.getDictionary().getMapping()[index];
    final DataType<?> type = this.definition.getDataType(attribute);
    
    // Init
    int[] order = new int[dictionary.length];
    for (int i = 0; i < order.length; i++) {
        order[i] = i;
    }
    
    // Sort
    Sorting.mergeSort(order, 0, order.length, new IntComparator() {
        @Override public int compare(int arg0, int arg1) {
            String value1 = dictionary[arg0];
            String value2 = dictionary[arg1];
            try {
                return type.compare(value1, value2);
            } catch (NumberFormatException | ParseException e) {
                throw new IllegalStateException(e);
            }
        }
    });
    
    // Return
    return order;
}
 
Example #6
Source File: GenericSorting.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sorts the specified range of elements according
 * to the order induced by the specified comparator.  All elements in the
 * range must be <i>mutually comparable</i> by the specified comparator
 * (that is, <tt>c.compare(a, b)</tt> must not throw an
 * exception for any indexes <tt>a</tt> and
 * <tt>b</tt> in the range).<p>
 *
 * This sort is guaranteed to be <i>stable</i>:  equal elements will
 * not be reordered as a result of the sort.<p>
 *
 * The sorting algorithm is a modified mergesort (in which the merge is
 * omitted if the highest element in the low sublist is less than the
 * lowest element in the high sublist).  This algorithm offers guaranteed
 * n*log(n) performance, and can approach linear performance on nearly
 * sorted lists.
 *
 * @param fromIndex the index of the first element (inclusive) to be sorted.
 * @param toIndex the index of the last element (exclusive) to be sorted.
 * @param c the comparator to determine the order of the generic data.
 * @param swapper an object that knows how to swap the elements at any two indexes (a,b).
 *
 * @see IntComparator
 * @see Swapper
 */
public static void mergeSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper) {
	/*
		We retain the same method signature as quickSort.
		Given only a comparator and swapper we do not know how to copy and move elements from/to temporary arrays.
		Hence, in contrast to the JDK mergesorts this is an "in-place" mergesort, i.e. does not allocate any temporary arrays.
		A non-inplace mergesort would perhaps be faster in most cases, but would require non-intuitive delegate objects...
	*/
	int length = toIndex - fromIndex;

	// Insertion sort on smallest arrays
	if (length < SMALL) {
		for (int i = fromIndex; i < toIndex; i++) {
			for (int j = i; j > fromIndex && (c.compare(j - 1, j) > 0); j--) {
				swapper.swap(j, j - 1);
			}
		}
		return;
	}

	// Recursively sort halves
	int mid = (fromIndex + toIndex) / 2;
	mergeSort(fromIndex, mid, c, swapper);
	mergeSort(mid, toIndex, c, swapper);

	// If list is already sorted, nothing left to do.  This is an
	// optimization that results in faster sorts for nearly ordered lists.
	if (c.compare(mid - 1, mid) <= 0) return;

	// Merge sorted halves 
	inplace_merge(fromIndex, mid, toIndex, c, swapper);
}
 
Example #7
Source File: GenericSorting.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(a,b);
	int ac = comp.compare(a,c);
	int bc = comp.compare(b,c);
	return (ab<0 ?
		(bc<0 ? b : ac<0 ? c : a) :
		(bc>0 ? b : ac>0 ? c : a));
}
 
Example #8
Source File: Partitioning.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(a,b);
	int ac = comp.compare(a,c);
	int bc = comp.compare(b,c);
	return (ab<0 ?
		(bc<0 ? b : ac<0 ? c : a) :
		(bc>0 ? b : ac>0 ? c : a));
}
 
Example #9
Source File: Partitioning.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
Same as {@link #partition(int[],int,int,int)} 
except that it <i>generically</i> partitions arbitrary shaped data (for example matrices or multiple arrays) rather than <tt>int[]</tt> arrays.
*/
private static int genericPartition(int from, int to, int splitter, IntComparator comp, Swapper swapper) {
	for (int i=from-1; ++i<=to; ) {
		if (comp.compare(splitter,i) > 0) {
			// swap x[i] with x[from]
			swapper.swap(i,from);
			from++;
		}
	}
	return from-1;
}
 
Example #10
Source File: GenericSorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Transforms two consecutive sorted ranges into a single sorted 
 * range.  The initial ranges are <code>[first, middle)</code>
 * and <code>[middle, last)</code>, and the resulting range is
 * <code>[first, last)</code>.  
 * Elements in the first input range will precede equal elements in the 
 * second.
 */
private static void inplace_merge(int first, int middle, int last, IntComparator comp, Swapper swapper) {
	if (first >= middle || middle >= last)
		return;
	if (last - first == 2) {
		if (comp.compare(middle, first)<0) {
			swapper.swap(first,middle);
		}
		return;
	}
	int firstCut;
	int secondCut;
	if (middle - first > last - middle) {
		firstCut = first + (middle - first) / 2;
		secondCut = lower_bound(middle, last, firstCut, comp);
	} 
	else {
		secondCut = middle + (last - middle) / 2;
		firstCut = upper_bound(first, middle, secondCut, comp);
	}

	// rotate(firstCut, middle, secondCut, swapper);
	// is manually inlined for speed (jitter inlining seems to work only for small call depths, even if methods are "static private")
	// speedup = 1.7
	// begin inline
	int first2 = firstCut; int middle2 = middle; int last2 = secondCut;
	if (middle2 != first2 && middle2 != last2) {
		int first1 = first2; int last1 = middle2;
		while (first1 < --last1) swapper.swap(first1++,last1);
		first1 = middle2; last1 = last2;
		while (first1 < --last1) swapper.swap(first1++,last1);
		first1 = first2; last1 = last2;
		while (first1 < --last1) swapper.swap(first1++,last1);
	}
	// end inline

	middle = firstCut + (secondCut - middle);
	inplace_merge(first, firstCut, middle, comp, swapper);
	inplace_merge(middle, secondCut, last, comp, swapper);
}
 
Example #11
Source File: Sorting.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int x[], int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(x[a],x[b]);
	int ac = comp.compare(x[a],x[c]);
	int bc = comp.compare(x[b],x[c]);
	return (ab<0 ?
	(bc<0 ? b : ac<0 ? c : a) :
	(bc>0 ? b : ac>0 ? c : a));
}
 
Example #12
Source File: Sorting.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private static void mergeSort1(int src[], int dest[], int low, int high, IntComparator c) {
	int length = high - low;
	
	// Insertion sort on smallest arrays
	if (length < SMALL) {
	    for (int i=low; i<high; i++)
			for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
			    swap(dest, j, j-1);
	    return;
	}

	// Recursively sort halves of dest into src
	int mid = (low + high)/2;
	mergeSort1(dest, src, low, mid, c);
	mergeSort1(dest, src, mid, high, c);

	// If list is already sorted, just copy from src to dest.  This is an
	// optimization that results in faster sorts for nearly ordered lists.
	if (c.compare(src[mid-1], src[mid]) <= 0) {
	   System.arraycopy(src, low, dest, low, length);
	   return;
	}

	// Merge sorted halves (now in src) into dest
	for(int i = low, p = low, q = mid; i < high; i++) {
		if (q>=high || p<mid && c.compare(src[p], src[q]) <= 0)
			dest[i] = src[p++];
		else
			dest[i] = src[q++];
	}
}
 
Example #13
Source File: GenericSorting.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Transforms two consecutive sorted ranges into a single sorted 
 * range.  The initial ranges are <code>[first, middle)</code>
 * and <code>[middle, last)</code>, and the resulting range is
 * <code>[first, last)</code>.  
 * Elements in the first input range will precede equal elements in the 
 * second.
 */
private static void inplace_merge(int first, int middle, int last, IntComparator comp, Swapper swapper) {
	if (first >= middle || middle >= last)
		return;
	if (last - first == 2) {
		if (comp.compare(middle, first)<0) {
			swapper.swap(first,middle);
		}
		return;
	}
	int firstCut;
	int secondCut;
	if (middle - first > last - middle) {
		firstCut = first + (middle - first) / 2;
		secondCut = lower_bound(middle, last, firstCut, comp);
	} 
	else {
		secondCut = middle + (last - middle) / 2;
		firstCut = upper_bound(first, middle, secondCut, comp);
	}

	// rotate(firstCut, middle, secondCut, swapper);
	// is manually inlined for speed (jitter inlining seems to work only for small call depths, even if methods are "static private")
	// speedup = 1.7
	// begin inline
	int first2 = firstCut; int middle2 = middle; int last2 = secondCut;
	if (middle2 != first2 && middle2 != last2) {
		int first1 = first2; int last1 = middle2;
		while (first1 < --last1) swapper.swap(first1++,last1);
		first1 = middle2; last1 = last2;
		while (first1 < --last1) swapper.swap(first1++,last1);
		first1 = first2; last1 = last2;
		while (first1 < --last1) swapper.swap(first1++,last1);
	}
	// end inline

	middle = firstCut + (secondCut - middle);
	inplace_merge(first, firstCut, middle, comp, swapper);
	inplace_merge(middle, secondCut, last, comp, swapper);
}
 
Example #14
Source File: GenericSorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(a,b);
	int ac = comp.compare(a,c);
	int bc = comp.compare(b,c);
	return (ab<0 ?
		(bc<0 ? b : ac<0 ? c : a) :
		(bc>0 ? b : ac>0 ? c : a));
}
 
Example #15
Source File: GenericSorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Sorts the specified range of elements according
 * to the order induced by the specified comparator.  All elements in the
 * range must be <i>mutually comparable</i> by the specified comparator
 * (that is, <tt>c.compare(a, b)</tt> must not throw an
 * exception for any indexes <tt>a</tt> and
 * <tt>b</tt> in the range).<p>
 *
 * This sort is guaranteed to be <i>stable</i>:  equal elements will
 * not be reordered as a result of the sort.<p>
 *
 * The sorting algorithm is a modified mergesort (in which the merge is
 * omitted if the highest element in the low sublist is less than the
 * lowest element in the high sublist).  This algorithm offers guaranteed
 * n*log(n) performance, and can approach linear performance on nearly
 * sorted lists.
 *
 * @param fromIndex the index of the first element (inclusive) to be sorted.
 * @param toIndex the index of the last element (exclusive) to be sorted.
 * @param c the comparator to determine the order of the generic data.
 * @param swapper an object that knows how to swap the elements at any two indexes (a,b).
 *
 * @see IntComparator
 * @see Swapper
 */
public static void mergeSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper) {
	/*
		We retain the same method signature as quickSort.
		Given only a comparator and swapper we do not know how to copy and move elements from/to temporary arrays.
		Hence, in contrast to the JDK mergesorts this is an "in-place" mergesort, i.e. does not allocate any temporary arrays.
		A non-inplace mergesort would perhaps be faster in most cases, but would require non-intuitive delegate objects...
	*/
	int length = toIndex - fromIndex;

	// Insertion sort on smallest arrays
	if (length < SMALL) {
		for (int i = fromIndex; i < toIndex; i++) {
			for (int j = i; j > fromIndex && (c.compare(j - 1, j) > 0); j--) {
				swapper.swap(j, j - 1);
			}
		}
		return;
	}

	// Recursively sort halves
	int mid = (fromIndex + toIndex) / 2;
	mergeSort(fromIndex, mid, c, swapper);
	mergeSort(mid, toIndex, c, swapper);

	// If list is already sorted, nothing left to do.  This is an
	// optimization that results in faster sorts for nearly ordered lists.
	if (c.compare(mid - 1, mid) <= 0) return;

	// Merge sorted halves 
	inplace_merge(fromIndex, mid, toIndex, c, swapper);
}
 
Example #16
Source File: Partitioning.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
Same as {@link #partition(int[],int,int,int)} 
except that it <i>generically</i> partitions arbitrary shaped data (for example matrices or multiple arrays) rather than <tt>int[]</tt> arrays.
*/
private static int genericPartition(int from, int to, int splitter, IntComparator comp, Swapper swapper) {
	for (int i=from-1; ++i<=to; ) {
		if (comp.compare(splitter,i) > 0) {
			// swap x[i] with x[from]
			swapper.swap(i,from);
			from++;
		}
	}
	return from-1;
}
 
Example #17
Source File: Partitioning.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(a,b);
	int ac = comp.compare(a,c);
	int bc = comp.compare(b,c);
	return (ab<0 ?
		(bc<0 ? b : ac<0 ? c : a) :
		(bc>0 ? b : ac>0 ? c : a));
}
 
Example #18
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the index of the median of the three indexed chars.
 */
private static int med3(int x[], int a, int b, int c, IntComparator comp) {
	int ab = comp.compare(x[a],x[b]);
	int ac = comp.compare(x[a],x[c]);
	int bc = comp.compare(x[b],x[c]);
	return (ab<0 ?
	(bc<0 ? b : ac<0 ? c : a) :
	(bc>0 ? b : ac>0 ? c : a));
}
 
Example #19
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void mergeSort1(int src[], int dest[], int low, int high, IntComparator c) {
	int length = high - low;
	
	// Insertion sort on smallest arrays
	if (length < SMALL) {
	    for (int i=low; i<high; i++)
			for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
			    swap(dest, j, j-1);
	    return;
	}

	// Recursively sort halves of dest into src
	int mid = (low + high)/2;
	mergeSort1(dest, src, low, mid, c);
	mergeSort1(dest, src, mid, high, c);

	// If list is already sorted, just copy from src to dest.  This is an
	// optimization that results in faster sorts for nearly ordered lists.
	if (c.compare(src[mid-1], src[mid]) <= 0) {
	   System.arraycopy(src, low, dest, low, length);
	   return;
	}

	// Merge sorted halves (now in src) into dest
	for(int i = low, p = low, q = mid; i < high; i++) {
		if (q>=high || p<mid && c.compare(src[p], src[q]) <= 0)
			dest[i] = src[p++];
		else
			dest[i] = src[q++];
	}
}
 
Example #20
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void runSort(int[] a, int fromIndex, int toIndex, IntComparator c) {
	cern.colt.Sorting.mergeSort(a,fromIndex,toIndex,c);
}
 
Example #21
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void runSort(int fromIndex, int toIndex, IntComparator c, cern.colt.Swapper swapper) {
	cern.colt.GenericSorting.mergeSort(fromIndex, toIndex, c, swapper);
}
 
Example #22
Source File: GenericSorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Performs a binary search on an already-sorted range: finds the last
 * position where an element can be inserted without violating the ordering.
 * Sorting is by a user-supplied comparison function.
 * @param array    Array containing the range.
 * @param first    Beginning of the range.
 * @param last     One past the end of the range.
 * @param x        Element to be searched for.
 * @param comp     Comparison function.
 * @return         The largest index i such that, for every j in the
 *                 range <code>[first, i)</code>, 
 *                 <code>comp.apply(x, array[j])</code> is 
 *                 <code>false</code>.
 * @see Sorting#lower_bound
 * @see Sorting#equal_range
 * @see Sorting#binary_search
 */
private static int upper_bound(int first, int last, int x, IntComparator comp) {
	//if (comp==null) throw new NullPointerException();
	int len = last - first;
	while (len > 0) {
		int half = len / 2;
		int middle = first + half;
		if (comp.compare(x, middle)<0) {
			len = half;
		}
		else {
			first = middle + 1;
			len -= half + 1;
		}
	}
	return first;
}
 
Example #23
Source File: GenericSorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Sorts the specified sub-array into ascending order.
 */
private static void quickSort1(int off, int len, IntComparator comp, Swapper swapper) {
	// Insertion sort on smallest arrays
	if (len < SMALL) {
		for (int i=off; i<len+off; i++)
		for (int j=i; j>off && (comp.compare(j-1,j)>0); j--) {
		    swapper.swap(j, j-1);
		}
		return;
	}

	// Choose a partition element, v
	int m = off + len/2;       // Small arrays, middle element
	if (len > SMALL) {
		int l = off;
		int n = off + len - 1;
		if (len > MEDIUM) {        // Big arrays, pseudomedian of 9
			int s = len/8;
			l = med3(l,     l+s, l+2*s, comp);
			m = med3(m-s,   m,   m+s, comp);
			n = med3(n-2*s, n-s, n, comp);
		}
		m = med3(l, m, n, comp); // Mid-size, med of 3
	}
	//long v = x[m];
	
	// Establish Invariant: v* (<v)* (>v)* v*
	int a = off, b = a, c = off + len - 1, d = c;
	while(true) {
		int comparison;
		while (b <= c && ((comparison=comp.compare(b,m))<=0)) {
			if (comparison == 0) {
				if (a==m) m = b; // moving target; DELTA to JDK !!!
				else if (b==m) m = a; // moving target; DELTA to JDK !!!
			    swapper.swap(a++, b);
			}
			b++;
		}
		while (c >= b && ((comparison=comp.compare(c,m))>=0)) {
			if (comparison == 0) {
				if (c==m) m = d; // moving target; DELTA to JDK !!!
				else if (d==m) m = c; // moving target; DELTA to JDK !!!
			    swapper.swap(c, d--);
			}
			c--;
		}
		if (b > c) break;
		if (b==m) m = d; // moving target; DELTA to JDK !!!
		else if (c==m) m = c; // moving target; DELTA to JDK !!!
		swapper.swap(b++, c--);
	}

	// Swap partition elements back to middle
	int s, n = off + len;
	s = Math.min(a-off, b-a  );  vecswap(swapper, off, b-s, s);
	s = Math.min(d-c,   n-d-1);  vecswap(swapper, b,   n-s, s);

	// Recursively sort non-partition-elements
	if ((s = b-a) > 1) 
		quickSort1(off, s, comp, swapper);
	if ((s = d-c) > 1) 
		quickSort1(n-s, s, comp, swapper);
}
 
Example #24
Source File: GenericSorting.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs a binary search on an already-sorted range: finds the last
 * position where an element can be inserted without violating the ordering.
 * Sorting is by a user-supplied comparison function.
 * @param array    Array containing the range.
 * @param first    Beginning of the range.
 * @param last     One past the end of the range.
 * @param x        Element to be searched for.
 * @param comp     Comparison function.
 * @return         The largest index i such that, for every j in the
 *                 range <code>[first, i)</code>, 
 *                 <code>comp.apply(x, array[j])</code> is 
 *                 <code>false</code>.
 * @see Sorting#lower_bound
 * @see Sorting#equal_range
 * @see Sorting#binary_search
 */
private static int upper_bound(int first, int last, int x, IntComparator comp) {
	//if (comp==null) throw new NullPointerException();
	int len = last - first;
	while (len > 0) {
		int half = len / 2;
		int middle = first + half;
		if (comp.compare(x, middle)<0) {
			len = half;
		}
		else {
			first = middle + 1;
			len -= half + 1;
		}
	}
	return first;
}
 
Example #25
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void runSort(int[] a, int fromIndex, int toIndex, IntComparator c) {
	cern.colt.Sorting.quickSort(a,fromIndex,toIndex,c);
}
 
Example #26
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void runSort(int fromIndex, int toIndex, IntComparator c, cern.colt.Swapper swapper) {
	cern.colt.GenericSorting.quickSort(fromIndex, toIndex, c, swapper);
}
 
Example #27
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
Sorts the vector into ascending order, according to the <i>natural ordering</i>.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort descending, use flip views ...
<p>
<b>Example:</b> 
<table border="1" cellspacing="0">
  <tr nowrap> 
	<td valign="top"><tt> 7, 1, 3, 1<br>
	  </tt></td>
	<td valign="top"> 
	  <p><tt> ==&gt; 1, 1, 3, 7<br>
		The vector IS NOT SORTED.<br>
		The new VIEW IS SORTED.</tt></p>
	</td>
  </tr>
</table>

@param vector the vector to be sorted.
@return a new sorted vector (matrix) view. 
		<b>Note that the original matrix is left unaffected.</b>
*/
public DoubleMatrix1D sort(final DoubleMatrix1D vector) {
	int[] indexes = new int[vector.size()]; // row indexes to reorder instead of matrix itself
	for (int i=indexes.length; --i >= 0; ) indexes[i] = i;

	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			double av = vector.getQuick(a);
			double bv = vector.getQuick(b);
			if (av!=av || bv!=bv) return compareNaN(av,bv); // swap NaNs to the end
			return av<bv ? -1 : (av==bv ? 0 : 1);
		}
	};

	runSort(indexes,0,indexes.length,comp);

	return vector.viewSelection(indexes);
}
 
Example #28
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
Sorts the matrix rows into ascending order, according to the <i>natural ordering</i> of the matrix values in the given column.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
To sort ranges use sub-ranging views. To sort columns by rows, use dice views. To sort descending, use flip views ...
<p>
<b>Example:</b> 
<table border="1" cellspacing="0">
  <tr nowrap> 
	<td valign="top"><tt>4 x 2 matrix: <br>
	  7, 6<br>
	  5, 4<br>
	  3, 2<br>
	  1, 0 <br>
	  </tt></td>
	<td align="left" valign="top"> 
	  <p><tt>column = 0;<br>
		view = quickSort(matrix,column);<br>
		System.out.println(view); </tt><tt><br>
		==> </tt></p>
	  </td>
	<td valign="top"> 
	  <p><tt>4 x 2 matrix:<br>
		1, 0<br>
		3, 2<br>
		5, 4<br>
		7, 6</tt><br>
		The matrix IS NOT SORTED.<br>
		The new VIEW IS SORTED.</p>
	  </td>
  </tr>
</table>

@param matrix the matrix to be sorted.
@param column the index of the column inducing the order.
@return a new matrix view having rows sorted by the given column.
		<b>Note that the original matrix is left unaffected.</b>
@throws IndexOutOfBoundsException if <tt>column < 0 || column >= matrix.columns()</tt>.
*/
public DoubleMatrix2D sort(DoubleMatrix2D matrix, int column) {
	if (column < 0 || column >= matrix.columns()) throw new IndexOutOfBoundsException("column="+column+", matrix="+Formatter.shape(matrix));

	int[] rowIndexes = new int[matrix.rows()]; // row indexes to reorder instead of matrix itself
	for (int i=rowIndexes.length; --i >= 0; ) rowIndexes[i] = i;

	final DoubleMatrix1D col = matrix.viewColumn(column);
	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			double av = col.getQuick(a);
			double bv = col.getQuick(b);
			if (av!=av || bv!=bv) return compareNaN(av,bv); // swap NaNs to the end
			return av<bv ? -1 : (av==bv ? 0 : 1);
		}
	};

	runSort(rowIndexes,0,rowIndexes.length,comp);

	// view the matrix according to the reordered row indexes
	// take all columns in the original order
	return matrix.viewSelection(rowIndexes,null);
}
 
Example #29
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
Sorts the matrix slices according to the order induced by the specified comparator.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
The algorithm compares two slices (2-d matrices) at a time, determinining whether one is smaller, equal or larger than the other.
To sort ranges use sub-ranging views. To sort by other dimensions, use dice views. To sort descending, use flip views ...
<p>
<b>Example:</b>
<pre>
// sort by sum of values in a slice
DoubleMatrix2DComparator comp = new DoubleMatrix2DComparator() {
&nbsp;&nbsp;&nbsp;public int compare(DoubleMatrix2D a, DoubleMatrix2D b) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;double as = a.zSum(); double bs = b.zSum();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return as < bs ? -1 : as == bs ? 0 : 1;
&nbsp;&nbsp;&nbsp;}
};
sorted = quickSort(matrix,comp);
</pre>

@param matrix the matrix to be sorted.
@param c the comparator to determine the order.
@return a new matrix view having slices sorted as specified.
		<b>Note that the original matrix is left unaffected.</b>
*/
public DoubleMatrix3D sort(final DoubleMatrix3D matrix, final DoubleMatrix2DComparator c) {
	int[] sliceIndexes = new int[matrix.slices()]; // indexes to reorder instead of matrix itself
	for (int i=sliceIndexes.length; --i >= 0; ) sliceIndexes[i] = i;

	final DoubleMatrix2D[] views = new DoubleMatrix2D[matrix.slices()]; // precompute views for speed
	for (int i=views.length; --i >= 0; ) views[i] = matrix.viewSlice(i);

	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			//return c.compare(matrix.viewSlice(a), matrix.viewSlice(b));
			return c.compare(views[a], views[b]);
		}
	};

	runSort(sliceIndexes,0,sliceIndexes.length,comp);

	// view the matrix according to the reordered slice indexes
	// take all rows and columns in the original order
	return matrix.viewSelection(sliceIndexes,null,null);
}
 
Example #30
Source File: Sorting.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
Sorts the matrix rows according to the order induced by the specified comparator.
The returned view is backed by this matrix, so changes in the returned view are reflected in this matrix, and vice-versa.
The algorithm compares two rows (1-d matrices) at a time, determinining whether one is smaller, equal or larger than the other.
To sort ranges use sub-ranging views. To sort columns by rows, use dice views. To sort descending, use flip views ...
<p>
<b>Example:</b>
<pre>
// sort by sum of values in a row
DoubleMatrix1DComparator comp = new DoubleMatrix1DComparator() {
&nbsp;&nbsp;&nbsp;public int compare(DoubleMatrix1D a, DoubleMatrix1D b) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;double as = a.zSum(); double bs = b.zSum();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return as < bs ? -1 : as == bs ? 0 : 1;
&nbsp;&nbsp;&nbsp;}
};
sorted = quickSort(matrix,comp);
</pre>

@param matrix the matrix to be sorted.
@param c the comparator to determine the order.
@return a new matrix view having rows sorted as specified.
		<b>Note that the original matrix is left unaffected.</b>
*/
public DoubleMatrix2D sort(final DoubleMatrix2D matrix, final DoubleMatrix1DComparator c) {
	int[] rowIndexes = new int[matrix.rows()]; // row indexes to reorder instead of matrix itself
	for (int i=rowIndexes.length; --i >= 0; ) rowIndexes[i] = i;

	final DoubleMatrix1D[] views = new DoubleMatrix1D[matrix.rows()]; // precompute views for speed
	for (int i=views.length; --i >= 0; ) views[i] = matrix.viewRow(i);

	IntComparator comp = new IntComparator() {  
		public int compare(int a, int b) {
			//return c.compare(matrix.viewRow(a), matrix.viewRow(b));
			return c.compare(views[a], views[b]);
		}
	};

	runSort(rowIndexes,0,rowIndexes.length,comp);

	// view the matrix according to the reordered row indexes
	// take all columns in the original order
	return matrix.viewSelection(rowIndexes,null);
}