[英]How can I combine shift element function to insertion sort?
I have a question: I was asked to write a function which related to insertion sort.我有一个问题:我被要求编写一个与插入排序相关的函数。 By giving a number the function will shift the next i values to the right, and to notice that the value at the last of the "i values" will get overrun by the previous one.通过给出一个数字,函数会将下一个 i 值向右移动,并注意到最后一个“i 值”的值将被前一个溢出。 For example: 9,8,7,6,5 and the number is i = 2: will become:9,8,7,7,6 while 5 got overrun.例如:9,8,7,6,5 并且数字是 i = 2: 将变成:9,8,7,7,6 而 5 被溢出。
So far that's the code I wrote:到目前为止,这是我写的代码:
public static void shift(int [] arr, int i) {
if(i < arr.length / 2) {
for(int j = i + i; j > i; j--) {
arr[j] = arr[j - 1];
}
}
else {
for(int j = arr.length - 1; j > i; j--) {
arr[j] = arr[j - 1];
}
}
}
Now I need to combine it with insertion sort and I tried with no success.现在我需要将它与插入排序结合起来,但我尝试没有成功。 Can someone help?有人可以帮忙吗? Thanks.谢谢。
What I got so far, I could be wrong, in that case please make comment so that I can correct.到目前为止我所得到的,我可能是错的,在这种情况下,请发表评论,以便我可以纠正。
public static void shift(int [] arr, int i)
{
if(i <= arr.length-2) // when i > (arr.length-2) shifting doesn't make any effect
{
int tmp = arr[i+1]; // tmp will hold the overwritten element for future use.
arr[i+1] = arr[i];
}
}
Now, do you want to sort it by insertion-sort?现在,您想通过插入排序对其进行排序吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.