Haxe Code Cookbook
Haxe programming cookbookData structuresSorting arrays

Sorting arrays

Sort an array of values

var myArray = [1,5,3,7,6,2,4];

myArray.sort(function(a, b):Int {
  if (a < b) return -1;
  else if (a > b) return 1;
  return 0;
});

This method isn't stable on all targets. If you need to retain the order of equal elements you should use haxe.ds.ArraySort

Using haxe.ds.ArraySort

var myArray = [1,5,3,7,6,2,4];

haxe.ds.ArraySort.sort(myArray, function(a, b):Int {
  if (a < b) return -1;
  else if (a > b) return 1;
  return 0;
});

Learn more about haxe.ds.ArraySort: https://api.haxe.org/haxe/ds/ArraySort.html

Usage

Simple array with ints

Array with objects

Notice how the second array, when using haxe.ds.ArraySort, keeps the order of the elements with equal i. The sorting is stable.


Contributors:
Last modified:
Created:
Category:  Data structures
Tags: