所以我试图将下面的代码变成递归方法,插入排序,但是尽管我尝试的却不能。任何人都可以帮助我吗?
public static void insertionSort(int[] array){
for (int i = 1; i < array.length; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
编辑: 我在考虑这样的事情,但对我来说看起来并不是很复杂......
public static void insertionSort(int[] array, int index){
if(index < array.length){
int j = index;
int B = array[index];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
insertionSort(array, index + 1);
}
}
答案 0 :(得分:13)
试试这个:
public class RecursiveInsertionSort {
static int[] arr = {5, 2, 4, 6, 1, 3};
int maxIndex = arr.length;
public static void main(String[] args) {
print(arr);
new RecursiveInsertionSort().sort(arr.length);
}
/*
The sorting function uses 'index' instead of 'copying the array' in each
recursive call to conserve memory and improve efficiency.
*/
private int sort(int maxIndex) {
if (maxIndex <= 1) {
// at this point maxIndex points to the second element in the array.
return maxIndex;
}
maxIndex = sort(maxIndex - 1); // recursive call
// save a copy of the value in variable 'key'.
// This value will be placed in the correct position
// after the while loop below ends.
int key = arr[maxIndex];
int i = maxIndex - 1;
// compare value in 'key' with all the elements in array
// that come before the element key.
while ((i >= 0) && (arr[i] > key)) {
arr[i+1] = arr[i];
i--;
}
arr[i+1] = key;
print(arr);
return maxIndex + 1;
}
// code to print the array on the console.
private static void print(int[] arr) {
System.out.println();
for (int i : arr) {
System.out.print(i + ", ");
}
}
}
答案 1 :(得分:3)
public static void insertionSort(int[] array, int index) {
if(array.length == index + 1) return;
insertionSort(array, index + 1);
// insert array[index] into the array
}
答案 2 :(得分:3)
您可以尝试使用此代码。它工作正常。
public static int[] InsertionSort(int[] dizi, int n)
{
int i;
if (n < 1) {
InsertionSort(dizi, n - 1);
}
else {
int key = dizi[n];
i = n - 1;
while (i >= 0 && dizi[i] > key) {
dizi[i + 1] = dizi[i];
i = i - 1;
}
dizi[i + 1] = key;
}
return dizi;
}
答案 3 :(得分:1)
对于递归算法,我们从整个数组A [1..n]开始,我们对A [1..n-1]进行排序,然后将A [n]插入正确的位置。
public int[] insertionSort(int[] array)
{
//base case
if(array.length==1) return new int[]{ array[0] };
//get array[0..n-1] and sort it
int[] arrayToSort = new int[array.length - 1]{ };
System.arraycopy(array, 0, arrayToSort, 0, array.length -1);
int[] B = insertionSort(arrayToSort);
//now, insert array[n] into its correct position
int[] C = merge(B, array[array.length - 1]);
return C;
}
private int[] merge(int[] array, int n)
{
int[] arrayToReturn = new int[array.length + 1] {};
int j = array.length-1;
while(j>=0 && n <= array[j])
{
arrayToReturn[j+1]=array[j;
j--;
}
arrayToReturn[j] =
}
答案 4 :(得分:0)
通过提供ele
作为整数数组来尝试以下代码,sortedIndex
=第一个元素的索引和index
=第二个元素的索引:
public static void insertionSort(int[] ele, int sortedIndex, int index) {
if (sortedIndex < ele.length) {
if (index < ele.length) {
if (ele[sortedIndex] > ele[index]) {
ele[sortedIndex] += ele[index];
ele[index] = ele[sortedIndex] - ele[index];
ele[sortedIndex] = ele[sortedIndex] - ele[index];
}
insertionSort(ele, sortedIndex, index + 1);
return;
}
if (index == ele.length) {
sortedIndex++;
}
insertionSort(ele, sortedIndex, sortedIndex + 1);
}
}
答案 5 :(得分:0)
var indexPath: IndexPath {
get {
// Return the internalIndexPath when we ask for the indexPath.
return internalIndexPath
}
set {
// Set the internalIndexPath to the value supplied to indexPath.
internalIndexPath = newValue
// Calculate the number of points on a post.
let points = model.dataContent[self.indexPath.row]["upVotes"].intValue - model.dataContent[self.indexPath.row]["downVotes"].intValue
pointsLabel.text = "\(points)"
// Show the upload time of the post.
let uploadTimeString = model.dataContent[self.indexPath.row]["timestamp"].stringValue
let date = DateFormatter.formatter.date(from: uploadTimeString)
let dateString = date?.relativeTime
uploadTime.text = dateString
if let type = MediaType(rawValue: model.dataContent[self.indexPath.row]["type"].stringValue) {
self.type = type
}
/// Adjust up/down arrows
if (model.dataContent[self.indexPath.row]["userVote"]["likeState"] != nil) {
switch model.dataContent[self.indexPath.row]["userVote"]["likeState"].stringValue {
case LikeState.Likes.rawValue:
thumbsUpButton.isSelected = true
thumbsDownButton.isSelected = false
case LikeState.Dislikes.rawValue:
thumbsUpButton.isSelected = false
thumbsDownButton.isSelected = true
case LikeState.Neither.rawValue:
thumbsUpButton.isSelected = false
thumbsDownButton.isSelected = false
default:
break
}
} else {
thumbsUpButton.isSelected = false
thumbsDownButton.isSelected = false
}
}
}
答案 6 :(得分:-1)
public class test
{
public static void main(String[] args){
test h = new test();
int a[] = { 5, 8, 9, 13, 65, 74, 25, 44, 67, 2, 1 };
h.ins_rec(a, a.length-1);
for(int i=0; i<a.length; i++)
log(a[i]);
}
void ins_rec(int a[], int j){
if( j == 0 ) return;
ins_rec(a, j - 1);
int key = a[ j ];
sort(a, key, j - 1);
}
void sort(int a[], int key, int i){
if( (i < 0) || (a[i] < key) ) {
a[ i + 1 ] = key;
return;
}
a[ i + 1 ] = a[ i ];
sort(a, key, i - 1);
}
private static void log(int aMessage){
System.out.println("\t\t"+aMessage);
}
}